Aalap Patel Aalap Patel - 6 months ago 18
Android Question

Not able to get value of an integer after callback method response

I have a method which makes an api call and parses response. I am getting integer value of current weather in onResponse method. I want to set this value to the textview but after onResponse method value doesnt preserve. I have made that variable as global too. And this class extends fragment so I am setting value in onViewCreated method.

here is the code of the method with logs...

public class HomeScreen extends Fragment{
int currentWeather = 0;

onViewCreated(){
curWeather = ... initialisation.
curWeather.setText(""+getCurrentWeather);
}

public int getCurrentWeather(){

OkHttpClient okHttpClient = new OkHttpClient();
Request re = new Request.Builder().url(forecastURL).build();
Call call = okHttpClient.newCall(re);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {

}

@Override
public void onResponse(Call call, Response response) throws IOException {
String jsonResponse = response.body().string();
JSONObject forecast;
JSONObject currently;
try {
forecast = new JSONObject(jsonResponse);
currently = forecast.getJSONObject("currently");
currentTempFaron = (int) Math.round(currently.getDouble("temperature"));
currentTempCelc = (currentTempFaron - 32) * 5 / 9;

Log.d("weather in try", "" + currentTempCelc); // has weather value
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("weather in response", "" + currentTempCelc); // again has weather value.
}
});
return currentTempCelc; //nothing it has at this point after coming out of response.
}

}

Answer

Do this inside onResponse() after Log.d("weather in response", "" + currentTempCelc);:

getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
        curWeather.setText(Integer.toString(currentTempCelc));
    }
});

The issue here is that you were trying to update the UI thread from the background thread which is not allowed. You can use runOnUiThread for this purpose though.

Comments