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;
}