【发布时间】:2019-01-15 05:45:30
【问题描述】:
我有两个全局变量 currentTemp 和 currentHum 在调用 Volley 的 onResponse 方法时设置。我的代码如下所示:
// Request a string response from the provided URL.
private JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, WEATHER_URL, null, new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONObject main = new JSONObject(response.getString("main"));
currentTemp = main.getString("temp");
currentHum = main.getString("humidity");
Log.i("RES", "Temp: " + main.getString("temp") + " Hum: " + main.getString("humidity"));
} catch (JSONException e) {
e.printStackTrace();
}
}}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(appContext, "An error occurred while retrieving weather info", Toast.LENGTH_LONG).show();
Log.e("ERR", "ERROR RET WEATHER DATA");
}
});
// Call the OpenWeatherMap API and get data such as temperature and humidity
private String getWeatherInfo(String key) {
// Add the request to the RequestQueue to invoke the API
queue.add(jsonObjectRequest);
// Access variables set by Volley's onResponse here.
switch (key) {
case "temp":
return String.valueOf(Float.parseFloat(currentTemp) - 273.15);
case "hum":
return currentHum;
default:
return " ";
}
}
我希望能够在调用它的getWeatherInfo 方法中访问由onResponse 方法设置的全局变量的值。然后将值传递给 switch 语句进行处理。如何在不为 currentTemp 和 currentHum 获取空值的情况下执行此操作?
【问题讨论】:
-
添加代码说明您如何执行
jsonObjectRequest并调用getWeatherInfo -
@MJM 我用类似的方式调用 getWeatherInfo:
"Its" + getWeatherInfo("temp") + "degrees celsius"
标签: android request android-volley