Android 在完成线程后设置文本

Android 在完成线程后设置文本,android,Android,我有个问题。为什么setText方法中的数据设置不正确 主要活动类 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textViewCity = (TextView) findViewById(R.id.text

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

主要活动类

@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和0表示textViewTemperature。

活动中的所有内容都在UI线程上执行。之所以会发生这种情况,是因为您正试图在使用
WeatherYahoo
启动新的
线程之后设置文本,所以您不必等待结果,只需输出空值。我建议您在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()));
     }
 }
private类WeatherYahooTask扩展异步任务{
受保护的天气背景(无效…参数){
//做任何你需要的工作(但不是在UI线程上)
// ...
回归天气;
}
执行后受保护的空(天气){
//在UI线程上做任何需要做的工作
textViewCity.setText(weather.getCity());
textViewTemperature.setText(String.valueOf(weather.getTemperature());
}
}
您有两个选项:

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

    Thread t = new Thread(new WeatherYahoo()).start();
    t.join();
    Weather weather = new Weather();
    
  • 或者您可以使用异步任务,如Yuriy posted
你能显示天气吗,构造器?看起来你在访问天气对象之前并没有设置任何属性。好的,我试试这个,但是当我在MainActivity类中有主屏幕并且我想要设置文本时,如何在WeatherYahoo中使用findViewById、setText等。你不需要使用“WeatherYahoo中的findViewById、setText等”。参见我添加的示例