【问题标题】:Why isn't my textview updating?为什么我的文本视图没有更新?
【发布时间】:2016-05-01 17:10:11
【问题描述】:

所以我有一个试图从异步任务更新的文本视图。我想更新它以正确打印到控制台的消息但由于某种原因它不会更新文本视图。以下是相关的代码:

public class MainActivity extends AppCompatActivity{
    private MqttClient client;
    private String clientId = MqttClient.generateClientId();
    private TextView tv;
    ...

我在这里声明了textview,然后在onCreate()方法中赋值:

tv = (TextView) findViewById(R.id.textView5);

然后在我的 asynctask 中,我有这个 sn-p,它会在每次将新消息发布到 MQTT 时运行:

@Override
        public void messageArrived(String topic, MqttMessage message)
                throws Exception {
            System.out.println(message);
            if(message.toString().toLowerCase().contains(str)){
                Pattern regex = Pattern.compile("(\\d+(?:\\.\\d+)?)");
                Matcher matcher = regex.matcher(message.toString());
                while(matcher.find()){
                    System.out.println(matcher.group(1));
                    tv.setText("testing");
                }
            }
        }

消息正确地将我想要的方式打印到控制台,但它没有更新文本视图,我不知道为什么。

【问题讨论】:

    标签: android android-asynctask textview


    【解决方案1】:

    确保在 UI 线程上调用回调 messageArrived。

    您可以从后台线程写入日志,但不能更新 UI 元素(如文本框)。

    您可以使用 runOnUIThread 从 UI 线程上的后台任务运行代码

        runOnUiThread(new Runnable() 
        {       
            public void run() 
            {
                // update UI code
            }
        });
    

    在您的情况下,这意味着将调用移动到回调(例如callback.messageArrived(..))或从可运行对象设置文本视图(tv.setText("testing");)

    【讨论】:

    • 非常感谢,我使用了 runOnUiThread 代码,现在可以使用了。我对 Android 编程比较陌生,所以学习线程和东西非常有趣。再次感谢!
    【解决方案2】:

    您应该在onPostExecute() 中更新您的TextView AsyncTask。

    这是一个例子

    protected void onPostExecute(Prams) {
    
        tv = (TextView) findViewById(R.id.textView5);
    
        tv.setText("testing");
    }
    

    这里的关键是您将protected doInBackground(Params) 的结果传递给onPostExecute(),它将更新您对UiThread 的看法。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-11
      • 1970-01-01
      相关资源
      最近更新 更多