【问题标题】:Getting force close on app when trying to setText() to TextView尝试将 setText() 设置为 TextView 时强制关闭应用程序
【发布时间】:2015-03-09 00:35:25
【问题描述】:

我制作了一个控制记分板的应用程序,我在我的 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;
    }
}

【问题讨论】:

    标签: java android android-asynctask textview


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      将与 UI 相关的代码从 doInBackground 移至 onPostExecute() 方法

      这里你需要移动这段代码

      redScore.setText(score);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-10-16
        • 2013-01-28
        • 2017-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多