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.