Skip to content Skip to sidebar Skip to footer

Can't Get ArrayList Outside Of For Loop In Call.enqueue

I want to get ArrayList data out of for loop from call.enqueue method in Retrofit. how to access lists outside of call.enqueue mehtod? Everything is working fine. When printing lis

Solution 1:

The simplest way might be to declare a function,

void accessArrayList(ArrayList<DanceSchool> danceSchool){
    //do stuff with the values
}

and call it inside call.enqueue

call.enqueue(new Callback<List<DanceSchool>>() {
    @Override
    public void onResponse(....) {
        ........
        List<DanceSchool> danceSchools = response.body();
        accessArrayList(danceSchools);
        .......
    }
}

Solution 2:

The point is: right now you are making an asynchronous call. You are requesting some information, and when that information has been compiled and is ready then that onResponse() method is invoked. Only then that list can be populated from the incoming response body.

So, what you could do is: have another method in your enclosing class, like updateList(), and then simply call that method from within your onResponse() implementation.

Beyond that, you might want to turn your asynchronous call into a synchronous one. Then, instead, you use execute() to wait for the result to come in (see here for example). But you would still need to have a callback method to call.

Alternatively, you could have a field within the enclosing class, like

List<DanceSchool> danceSchools
...
private void getSchoolList() {
  final Call<List<DanceSchool>> call = ...    
  call.enqueue(new Callback<List<DanceSchool>>() {
    @Override
    public void onResponse(Call<List<DanceSchool>> call, Response<List<DanceSchool>> response) {
    ...
    danceSchools.addAll(response.body());

Post a Comment for "Can't Get ArrayList Outside Of For Loop In Call.enqueue"