我试图返回的ArrayList是空的,即使在onResponse方法中添加了对象。 我怀疑方法getEvents在对象实际添加到ArrayList之前返回空的ArrayList。 队列处理完请求后是否有调用方法?
public class CustomRestRequestArray {
Authorizer authorizer;
ArrayList<Event> events;
public ArrayList<Event> getEvents(Context context, String url) throws JSONException {
events = new ArrayList<>();
authorizer = new Authorizer(context);
RequestQueue queue = Volley.newRequestQueue(context);
JsonObjectRequest getRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonEvents = response.getJSONArray("data");
for (int i=0; i< jsonEvents.length(); i++){
JSONObject obj = jsonEvents.getJSONObject(i);
Event event = new Event(
obj.getInt("id"),
obj.getString("name"),
obj.getString("description"),
obj.getString("start"),
obj.getString("end"),
obj.getBoolean("isPublic"),
obj.getString("address")
);
events.add(event);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "error => " + error.toString());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + authorizer.getToken());
return params;
}
};
queue.add(getRequest);
return events;
}
}