我需要返回我的ArrayList但是当我调用'volleyReq'时我收到null。请告诉我我做错了什么?当内部有空时如何返回值。我想我应该使用界面,但我不知道如何。谢谢。
public static ArrayList<KladrObject> volleyReq(String contentType,String limit,String query) {
final String url = new StringBuilder().append("http://kladr-api.ru/api.php?").append("query=" + query).append("&contentType="+contentType).append("&limit="+limit).append("&token=MY KEY").toString();
final ArrayList<KladrObject> arr = new ArrayList<KladrObject>();
final JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//JSONArray array = response.getJSONArray("result");
try{
JSONArray array = response.getJSONArray("result");
for (int i = 0;i<array.length();i++) {
KladrObject kladrObject = new KladrObject();
kladrObject.setName(array.getJSONObject(i).getString("name"));
kladrObject.setType(array.getJSONObject(i).getString("type"));
kladrObject.setShortype(array.getJSONObject(i).getString("typeShort"));
arr.add(kladrObject);
}
}catch (JSONException e){
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Do what you want to do on error
}
});
AppController.getInstance().getRequestQueue().add(req);
return arr;
}
答案 0 :(得分:0)
因为JsonObjectRequest在另一个线程上执行,所以你得到一个null。因此,当方法返回时,arr为空。
要实现您要执行的操作,您可以在需要响应的类中传入Response.Listener
和Response.ErrorListener
。因此,您的volleyReq
方法将如下所示:
public static void volleyReq(String contentType,String limit,String query, Response.Listener responseListesner, Response.ErrorListener errorListener)
{
final String url = new StringBuilder().append("http://kladr-api.ru/api.php?").append("query=" + query).append("&contentType="+contentType).append("&limit="+limit).append("&token=MY KEY").toString();
final ArrayList<KladrObject> arr = new ArrayList<KladrObject>();
final JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url,
responseListener, errorListener);
}
您的方法调用将如下所示:
final ArrayList<KladrObject> arr = new ArrayList<KladrObject>();
volleyReq("application/json", 100, "searchQuery", new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//JSONArray array = response.getJSONArray("result");
try{
JSONArray array = response.getJSONArray("result");
for (int i = 0;i<array.length();i++) {
KladrObject kladrObject = new KladrObject();
kladrObject.setName(array.getJSONObject(i).getString("name"));
kladrObject.setType(array.getJSONObject(i).getString("type"));
kladrObject.setShortype(array.getJSONObject(i).getString("typeShort"));
arr.add(kladrObject);
}
}catch (JSONException e){
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Do what you want to do on error
}
});