【发布时间】:2016-05-28 04:00:55
【问题描述】:
我有一个方法可以进行 api 调用并解析响应。我在 onResponse 方法中获取当前天气的整数值。我想将此值设置为 textview 但在 onResponse 方法值不保留之后。我也将该变量设为全局变量。这个类扩展了片段,所以我在 onViewCreated 方法中设置值。
这里是带有日志的方法的代码...
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.
}
}
【问题讨论】:
-
您看到错误还是您的视图没有更新?
-
不明白先生...
-
我的视图没有更新,因为我的方法返回默认值 0
-
好的,你知道你收到了一个有效的 JSON 响应吗?
-
是的,这是有效的,我在日志语句中得到的值是完美的
标签: java android android-fragments