请任何人帮助我,我的代码中的列表大小返回零 注意: - 当获取大小为零返回时,列表是全局变量
15
感谢所有
答案 0 :(得分:0)
Volley不是同步的,它接受请求并在请求完成时给你回调。如果在调用onResponse后检查大小,您将获得所需的结果
String url = "http://api.openweathermap.org/data/2.5/weather?q=" + cities + "&APPID=8072ed7ede0fc9bcb8591a2a2eb90cfd";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
CityWeather cityWeather = new CityWeather();
JSONObject object = new JSONObject(response);
cityWeather.setLonitude(String.valueOf(object.getJSONObject("coord").getDouble("lon")));
cityWeather.setLatitude(String.valueOf(object.getJSONObject("coord").getDouble("lat")));
cityWeather.setCityName(object.getString("name"));
cityWeather.setCurrentTemp(String.valueOf(object.getJSONObject("main").getDouble("temp")));
cityWeather.setPressure(String.valueOf(object.getJSONObject("main").getInt("pressure")));
cityWeather.setHumidity(String.valueOf(object.getJSONObject("main").getInt("humidity")));
cityWeather.setMinTemp(String.valueOf(object.getJSONObject("main").getDouble("temp_min")));
cityWeather.setMaxTemp(String.valueOf(object.getJSONObject("main").getDouble("temp_max")));
cityWeather.setWindSpeed(String.valueOf(object.getJSONObject("wind").getDouble("speed")));
cityWeather.setWindDegree(String.valueOf(object.getJSONObject("wind").getInt("deg")));
list.add(cityWeather);
//Check list size here and do whatever you want with the list
} catch (JSONException e) {
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);