简体   繁体   中英

Android Error Returning a null value from Thread

I created this application to get the wether details to my app.

I have a GetWeather Class in my Android App whre i have GetWeather method which returns a string. but when i try to get value form that class which consist of a thread. i always get a null value. Please refer my code kindly and tell me where i got wrong. Thank you

Main Activity

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


                Button b1 = (Button) findViewById(R.id.showData);

                b1.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {


                    GetWeather1 gw = new GetWeather1();
                    String weather = gw.GetWeather1 ("CA","Anuradhapura");

                    Toast.makeText(getApplicationContext(), " Weather condition is " + weather, Toast.LENGTH_SHORT).show();


                    }
                });
            }


    // This is GetWeather  class

        public class GetWeather {



            public String weather;
            public String temperature_string;
            public Bitmap weather_icon;

            public GetWeather() {

            }

            public  String GetWeather(String city, String state) {

                city = city.replaceAll(" ", "_");
                // construct post URL
                final String GET_WEATHER_URL = WEATHER_URL + state + "/" + city
                        + ".json";
                new Thread(new Runnable() {
                    public void run() {
                        String request = GET_WEATHER_URL;
                        HttpResponse rp = null;
                        JSONObject jObject = null;
                        try {
                            HttpClient httpclient = new DefaultHttpClient();
                            httpclient.getParams().setParameter(
                                    CoreProtocolPNames.PROTOCOL_VERSION,
                                    HttpVersion.HTTP_1_1);
                            HttpGet request1 = new HttpGet(
                                    "http://api.wunderground.com/api/key/conditions/q/CA/Anuradhapura.json");
                            HttpResponse response = httpclient.execute(request1);
                            HttpEntity resEntity = response.getEntity();
                            String _response = EntityUtils.toString(resEntity);
                            jObject = new JSONObject(_response);
                            JSONObject current_observation = jObject.getJSONObject("current_observation");
                            temperature_string = current_observation.getString("temperature_string");
                            weather = current_observation.getString("weather");
                            Log.i("..............", "" + weather);
                            Log.i("..............", "" + temperature_string);




                            String icon_url = current_observation.getString("icon_url");
                            weather_icon = get_weather_icon(icon_url);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }).start();

                 while (weather != null) {

                    }

                    return weather;


            }

The condition while(whether != null) should be while(whether == null) to wait for a Thread to complete its task. But it will wait on UI Thread which may result in ANR error.

Instead use AsyncTask and get the result in onPostExecute() ...

and with respect to your comments, This may help you.

public class WeatherTask extends AsyncTask<String, Void, String[]> {

    @Override
    protected String[] doInBackground(String... params) {
        String city = params[0];
        String state = params[1];

        city = city.replaceAll(" ", "_");
        // construct post URL
        final String GET_WEATHER_URL = WEATHER_URL + state + "/" + city
                + ".json";
        String request = GET_WEATHER_URL;
        HttpResponse rp = null;
        JSONObject jObject = null;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            httpclient.getParams().setParameter(
                    CoreProtocolPNames.PROTOCOL_VERSION,
                    HttpVersion.HTTP_1_1);
            HttpGet request1 = new HttpGet(
                    "http://api.wunderground.com/api/key/conditions/q/CA/Anuradhapura.json");
            HttpResponse response = httpclient.execute(request1);
            HttpEntity resEntity = response.getEntity();
            String _response = EntityUtils.toString(resEntity);
            jObject = new JSONObject(_response);
            JSONObject current_observation = jObject
                    .getJSONObject("current_observation");
            String temperature_string = current_observation
                    .getString("temperature_string");
            String weather = current_observation.getString("weather");
            Log.i("..............", "" + weather);
            Log.i("..............", "" + temperature_string);
            String icon_url = current_observation.getString("icon_url");
            String weather_icon = get_weather_icon(icon_url);
            String[] out = new String[]{weather,weather_icon,temperature_string};
            return out;
        } catch (Exception exception) {

        }
        return null;
    }

    @Override
    protected void onPostExecute(String[] result) {
        if(result != null) {
            String weather = result[0];
            String weather_icon = result[1];
            String temperature_string = result[2];
        }
    }
}

and start this task in onButtonClick() like

  new WeatherTask().execute("CA","Anuradhapura");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM