0

I am trying to return arrayList to fill up a recyclerview, when i debug y stop in response everything goes god, but when i stop in return, arrayList is empty

This is my code:

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;

And arrayList dont have anything, and my response is thisone

{
"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"
    }
]
}

i see in debug mode array is geting correctly, but arraylist comes empty

someone know why?

1 Answers1

2

Volley is asynchronous, so you are returning an empty list before Volley actually executes onResponse.

Therefore, you can't just "return an ArrayList" from a method that runs Volley.

You need to put arrayList.add() within onResponse and notify your RecyclerView adapter after the loop over the JSONArray.

You should also change that method to be void to not confuse yourself.


One pattern I recommend people follow is to use callbacks

public void getArrayList(final String token,
     MatchListAsyncResponse callback) {
             List<MyMatch> arrayList = new ArrayList<>();

             for (int i = 0; i < n; i++) {
                ... 
                arrayList.add(myMatch);
             } 
             if (null != callback) callback.processFinish(arrayList);

The general implementation of MatchListAsyncResponse can be taken from

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

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

Whether you use Volley or AsyncTask, the callback concept is the same. Use interfaces to pass back the data to where it was called.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245