【问题标题】:Set text after complete thread完成线程后设置文本
【发布时间】:2015-06-01 19:33:06
【问题描述】:

我有问题。为什么 setText 方法中的数据设置不正确?

MainActivity 类

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textViewCity = (TextView) findViewById(R.id.text_view_city_name);
        textViewTemperature = (TextView) findViewById(R.id.text_view_current_temperature);

        new Thread(new WeatherYahoo()).start();

        Weather weather = new Weather();

        textViewCity.setText(weather.getCity());
        textViewTemperature.setText(String.valueOf(weather.getTemperature()));
    }

数据已在 Weather 类中正确下载并设置(我使用 JSON),但屏幕上显示 textViewCity 形式为空字符串,textViewTemperature 为 0。

【问题讨论】:

标签: android


【解决方案1】:

活动中的所有内容都在 UI 线程上执行。之所以发生这种情况,是因为您尝试在使用WeatherYahoo 启动新的Thread 后立即设置文本,因此您无需等待结果,而只需输出空值。我建议您使用 AsyncTask 进行此类调用并在 UI 线程上检索结果。因此,您可以在doInBackground() 方法中完成您在WeatherYahoo 类中所做的所有工作,并在onPostExecute() 方法中输出结果。举个例子:

 private class WeatherYahooTask extends AsyncTask<Void, Void, Weather> {
     protected Weather doInBackground(Void... params) {
         // do any kind of work you need (but NOT on the UI thread)
         // ...
         return weather;
     }

     protected void onPostExecute(Weather weather) {
        // do any kind of work you need to do on UI thread
        textViewCity.setText(weather.getCity());
        textViewTemperature.setText(String.valueOf(weather.getTemperature()));
     }
 }

【讨论】:

  • 好的,我试试这个,但是当我在 MainActivity 类中有主屏幕并且我想要设置文本时,如何在 WeatherYahoo 中使用 findViewById、setText 等。
  • 您不需要在 WeatherYahoo 中使用“findViewById、setText 等”。查看我添加的示例
【解决方案2】:

你有两个选择:

  • 等待线程完成下载 json 使用:

    Thread t = new Thread(new WeatherYahoo()).start();
    t.join();
    Weather weather = new Weather();
    
  • 或者您可以使用 Yuriy 发布的异步任务。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 2018-01-30
    • 1970-01-01
    相关资源
    最近更新 更多