-2

I have a problem. Why a data in setText method are set incorrecetly?

MainActivity class

@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()));
    }

Data were downloaded and set correctly in Weather class (I use JSON) but on the screen showed empty string form textViewCity and 0 for textViewTemperature.

jjcool
  • 61
  • 5

2 Answers2

3

Everything in your activity executes on the UI thread. So this is happening because you are trying to set the text right after you started a new Thread with WeatherYahoo, so you don't wait for the result, but just output empty value. I would recommend you to use AsyncTask for such kind of calls and retrieving results on UI thread. So you can do all your work you do in WeatherYahoo class in doInBackground() method instead and output the result in onPostExecute() method. As an example:

 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()));
     }
 }
yyunikov
  • 5,719
  • 2
  • 43
  • 78
  • Ok, I try this, but how to use findViewById, setText etc in WeatherYahoo when I have main screen in MainActivity class and I want there set text. – jjcool Jun 01 '15 at 19:44
  • You don't need to use "findViewById, setText etc in WeatherYahoo". See the example I've added – yyunikov Jun 01 '15 at 19:51
0

You have 2 options:

  • Wait for the thread to finish downloading the json using:

    Thread t = new Thread(new WeatherYahoo()).start();
    t.join();
    Weather weather = new Weather();
    
  • Or you can use asynctasks like Yuriy posted.
muchwow
  • 715
  • 7
  • 22