2015-06-01 37 views
-2

我遇到問題。爲什麼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())); 
    } 

數據被下載和天氣類(我用JSON)設置正確,但是在屏幕上顯示的textViewTemperature空字符串形式textViewCity和0。

+0

可以顯示天氣,構造函數嗎? – jumojer

+0

在訪問天氣對象之前,它看起來並沒有設置天氣對象的任何屬性。 – jwBurnside

+0

http://stackoverflow.com/questions/18898039/using-asynctask/18898105?s=2|4.1738#18898105 – codeMagic

回答

3

活動中的所有內容都在UI線程上執行。所以發生這種情況的原因是,在開始一個新的ThreadWeatherYahoo之後,您正試圖設置文本,因此您不會等待結果,而只是輸出空值。我建議你使用AsyncTask進行這種調用並在UI線程中檢索結果。因此,您可以在WeatherYahoo課程中使用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())); 
    } 
} 
+0

好吧,我試試這個,但如何在WeatherYahoo中使用findViewById,setText等,當我在MainActivity中擁有主屏幕上課,我想那裏設置文本。 – jjcool

+0

你不需要在WeatherYahoo中使用「findViewById,setText等」。查看我添加的示例 –

+0

謝謝@Yuriy :) – jjcool

0

你有2種選擇:

  • 等待線程完成下載使用JSON:

    Thread t = new Thread(new WeatherYahoo()).start(); 
    t.join(); 
    Weather weather = new Weather(); 
    
  • 或者像尤里發佈,您可以使用asynctasks。