How to properly write a volley callback

Vasko Vasilev :

I am trying to write a volley get a request to fetch me all the users of my API. I have successfully done this, however, my function has stopped working. If I run my code now and attempt to fetch all the users, it will just return an empty array. If I try to fetch them one more time without stopping the run, it will return to me all of the users.

This is my function:

public ArrayList<User> getAllUsers(final VolleyCallBack callBack) {
    requestQueue = Volley.newRequestQueue(this);
    JsonArrayRequest arrayRequest = new JsonArrayRequest(
        Request.Method.GET,
        "http://ecoproduce.eu/api/User",
        null,
        new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                Log.e("Rest response", response.toString());

                Gson gson = new Gson();
                User user = new User();

                for (int i = 0; i < response.length(); i++) {
                    try {
                        user = gson.fromJson(response.getJSONObject(i).toString(), User.class);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    allUsers.add(user);
                }
                callBack.onSuccess();
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Error response", error.toString());
            }
        }
    );
    requestQueue.add(arrayRequest);
    return allUsers;
}

This is my callback interface:

public interface VolleyCallBack {
    ArrayList<User> onSuccess();
}

This is how I call the function:

ArrayList<User> currentUsers;

currentUsers = getAllUsers(new VolleyCallBack() {
        @Override
        public ArrayList<User> onSuccess() {
            Log.e("Bla", "ALL DONE!!!");
            return allUsers;
        }
    });

I don't know what the problem is, this was working perfectly like an hour ago but for some reason, it has stopped. This is my first attempt at writing RESTful requests and I can't really pinpoint the error of my code.

SOLUTION:

Problem solved by making the changes suggested by Reaz Murshed and moving the getAllUsers call to the body of onCreate insted of it being within the onClick() function.

Reaz Murshed :

The getAllUsers function is returning allUsers immediately after putting a get request in a background thread. That being said, you are getting the user list when the background thread for your API was not finished fetching your user list and hence you are getting an empty list for the first time.

However, during the second time, you are having it, because the first API request fetched the users successfully and updated your allUsers list. So, actually you are not getting the user list from the second time API request, you are getting it from the request that was made previously.

To tackle this problem, do not return the allUsers from your getAllUsers function immediately after sending the API request. Wait for the API request to fetch the data for you and you already have a setup for success callback, where you should be able to get your desired user data.

Hence, you need to implement your onSuccess method in your Activity or Fragment or wherever you are calling the getAllUsers method, and perform necessary actions with the list of users on receiving a successful callback.

I would suggest modifying your callback function a little so that you can actually pass on the information that you fetched from the server.

public interface VolleyCallBack {
    void onSuccess(ArrayList<User>);
}

And in the onResponse function of Volley callback, pass the user list that was fetched as follows.

callBack.onSuccess(allUsers);

I hope that helps!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=25281&siteId=1