gpt4 book ai didi

java - 回调方法响应后无法获取整数值

转载 作者:行者123 更新时间:2023-12-01 09:52:55 24 4
gpt4 key购买 nike

我有一个方法可以进行 api 调用并解析响应。我在 onResponse 方法中获取当前天气的整数值。我想将此值设置为 textview 但在 onResponse 方法之后值不保留。我也将该变量设置为全局变量。这个类扩展了 fragment ,所以我在 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.
}

}

最佳答案

onResponse() 内执行此操作之后Log.d("weather in response", "" + currentTempCelc); :

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

这里的问题是您试图从后台线程更新 UI 线程,这是不允许的。您可以使用runOnUiThread但出于这个目的。

关于java - 回调方法响应后无法获取整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37495050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com