尝试将 Text() 设置为文本视图时强制关闭应用程序



我做了一个控制记分板的应用程序,我在java应用程序上使用socketServers,在我的应用程序上使用socket。问题是我从服务器接收数据,但是当我尝试将其设置为 TextView 时,应用程序强制关闭。这是代码,我对android/Java编程非常陌生,我不知道使用AsyncTask是否会导致问题。

private class SendMessage extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        try {
            client = new Socket("192.168.11.23", 4444);
            printwriter = new PrintWriter(client.getOutputStream(), true);
            printwriter.write(message);
            printwriter.flush();
            InputStream is = client.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            score = br.readLine();
            Log.i("TEST", "--> " + score + " <--");
            redScore.setText(score);
            client.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

不能在后台线程中进行任何 UI 操作。这就是您的应用程序崩溃的原因。继续的方法是在 doInBackground 中返回文本或将此文本存储在 class 属性中,并使用同一AsyncTaskonPostExecute来分配此值,因为此方法是在 UI 线程中调用的。

将 UI 相关代码从 doInBackground 移动到 onPostExecute() 方法

在这里你需要移动这个代码

redScore.setText(score);

相关内容

最新更新