尝试将 setText() 设置为 TextView 时强制关闭应用程序

Getting force close on app when trying to setText() to TextView

我制作了一个控制记分牌的应用程序,我在 java 应用程序上使用了 socketServers,并在我的应用程序上使用了一个套接字。问题是我从服务器接收数据,但是当我试图将其设置为 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 操作。这就是您的应用程序崩溃的原因。进行的方法是returndoInBackground中的文本或将此文本存储在class属性中,并使用相同AsyncTaskonPostExecute来赋值这个值,因为这个方法是在 UI 线程中调用的。

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

这里你需要移动这段代码

redScore.setText(score);