使用 volley 从方法返回 ArrayList

Returning an ArrayList from a method by using volley

我正在尝试 return arrayList ,但 return arrayList 为空。当我 return arrayList 但它不起作用时我会使用。

 public ArrayList<Cities> getCities(){
    final ArrayList<Cities> cities=new ArrayList<>();
    String url = "http://10.0.2.2:3000/cities";
    mQueue = Volley.newRequestQueue(context);
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray jsonArray = response.getJSONArray("city");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject city = jsonArray.getJSONObject(i);
                            String id = city.getString("_id");
                            String name = city.getString("name");
                            Cities p=new Cities(id,name);
                            cities.add(p);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    mQueue.add(request);
return cities;
}

您的问题是您正在尝试 return 尚未填写的内容,调用是异步的,因此可能需要一些时间才能将日期填写到您的 ArrayList<Cities>,这就是为什么它是空的。

您应该删除此行 return cities; 并记住在您的方法之外创建此 final ArrayList<Cities> cities=new ArrayList<>();,并将 return ArrayList<Cities> 删除为 void

然后,您可以创建回调以通知数据已填充到您的 ArrayList<Cities>,如果您尝试将这些填充到 RecyclerView,我建议您将适配器设置为 onResponse()方法。

要执行回调操作,您可以查看此 or this Gist

如果您的响应 returns 一个包含城市元素数组的 JSONObject,则您的请求是正确的,但如上所述,在调用回调之前您不能期望实际得到结果。这是一个使用 JSONArrayRequest 的示例,其中 returns 一个 JSONArray,但在您从 JSONObject 中提取城市数组后,它的工作方式与您的几乎相同。

    private ListView mTripList;
public ArrayList<TripItem> tripItems;
private JSONArray unclaimedTrips;
private TripSelectAdapter adapter;



public void getTrips() {

        JsonArrayRequest req = new JsonArrayRequest(url, new Response.Listener<JSONArray> () {  

        @Override
        public void onResponse(JSONArray response) {

            // Public Array
            unclaimedTrips = response;

            tripItems = new ArrayList<TripItem>();


            // Optional if you want to manipulate the data in some way
            if (unclaimedTrips != null) {

                for (int i = 0; i < unclaimedTrips.length(); i++) {

                    try {
                        JSONObject item = unclaimedTrips.getJSONObject(i);

                        int tripID = item.getInt("trip_id");
                        int claimID = item.getInt("claim_id");
                        String payrollCode = item.getString("payroll_code");
                        String tripDate = item.getString("trip_date");
                        String tripPurpose = item.getString("trip_purpose");

                        TripItem tripItem = new TripItem(tripID, claimID, payrollCode, tripDate, tripPurpose);

                        tripItems.add(tripItem);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                refreshData();
            }

        }


    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            unclaimedTrips = null;
            refreshData();

        }
    }) {

       @Override
       public Map<String, String> getHeaders() throws AuthFailureError {
           HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Accept", "application/json");
                headers.put("Content-Type", "application/json");
           return headers;
       };
    };


    // add the request object to the queue to be executed
    MyApplication.getInstance().addToRequestQueue(req);
}


public void refreshData() {

    if (tripItems.isEmpty()) {
        mEmptyList.setVisibility(android.view.View.VISIBLE);
    } else {
        mEmptyList.setVisibility(android.view.View.GONE);                   
    }

    adapter = new TripSelectAdapter(this, thisContext, tripItems);
    mTripList.setAdapter(adapter);
}