在android中使用volley返回一个ArrayList

时间:2017-08-05 19:26:06

标签: android arraylist android-volley

我正在尝试返回arrayList来填充一个recyclerview,当我调试y停止响应一切都是上帝,但当我停止返回时,arrayList是空的

这是我的代码:

public static final String URL = "http://192.168.1.38/yoap/api/v1.0/amymatch";

Context context;
ArrayList<MyMatch> arrayList = new ArrayList<>();

MyMatch myMatch;

public MyMatchBackground(Context context) {

    this.context = context;

}

public ArrayList<MyMatch> getArrayList(final String token) {

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null,

            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        JSONArray jsonArray = response.getJSONArray("match");
                        int n = jsonArray.length();
                        for (int i = 0; i < n; i++) {
                            JSONObject object = jsonArray.getJSONObject(i);
                            String date = object.getString("date");
                            String time = object.getString("time");
                            String club = object.getString("club");
                            String level = object.getString("level");
                            myMatch = new MyMatch(date, time, club, level);
                            myMatch.setClubName(club);
                            myMatch.setDate(date);
                            myMatch.setTime(time);
                            myMatch.setLevel(level);
                            arrayList.add(myMatch);
                        }
                    } catch (JSONException e) {
                        Toast.makeText(context, "Error Exception", Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
            error.printStackTrace();
        }
    }){

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> hashMap =  new HashMap<String, String>();

            hashMap.put("Accept", "application/json");
            hashMap.put("Authorization", "Bearer "+ token);
            return hashMap;
        }
    };
MySingleton.getmInstance(context).addToRequestque(jsonObjectRequest);


    return arrayList;

而arrayList没有任何东西,我的回答就是这个

{
"match": [
    {
        "date": "05/08/2017",
        "time": "8:15",
        "club": "sport center",
        "level": "Masculino C"
    },
    {
        "date": "01/09/2017",
        "time": "22:15",
        "club": "sport center",
        "level": "Masculino D"
    }
]
}

我在调试模式中看到数组正确,但是arraylist是空的

有人知道为什么吗?

1 个答案:

答案 0 :(得分:1)

Volley是异步的,所以你在之前返回一个空列表,Volley实际执行onResponse

因此,您不能只从运行Volley的方法中“返回一个ArrayList”。

您需要将arrayList.add()放在onResponse 之内,然后在循环JSONArray之后通知您的RecyclerView适配器。

您还应该将该方法更改为无效,以免混淆自己。

我建议人们遵循的一种模式是使用回调

public void getArrayList(final String token,
     MatchListAsyncResponse callback) {
             .... 
             for (int i = 0; i < n; i++) {
                ... 
                arrayList.add(myMatch);
             } 
             if (null != callback) callback.processFinish(arrayList);

MatchListAsyncResponse的一般实施可以从

中获取

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

public interface MatchListAsyncResponse {
    void processFinish(List<Match> matches);
}

无论您使用Volley还是AsyncTask,回调概念都是一样的。使用接口将数据传回到调用它的位置。