0

The problem is that the global variable "responseDogs" is being returned as null at the end of method, but is populated inside onResponse method!?

Code:

public class DogREST {


private List<Dog> responseDogs;

//...


public List<Dog> retrieveDogsFromREST() {


    final DogService dogService = DogService.serviceDog;


    dogService.getDogs(AuthRequest.createAuthJsonString()).enqueue(new Callback<DogList>() {
        @Override
        public void onResponse(Call<DogList> call, Response<DogList> response) {

            if (response.isSuccessful()) {

                responseDogs = response.body().getDogs();


                Log.d("DogRESTSuccessful", "" + response.body().getDogs());
                Log.d("dogsReceived - >", "" + responseDogs);


            } else {

                Log.d("DogRESTNSuccessful", "- statusCode" + response.code());

            }

        }


        @Override
        public void onFailure(Call<DogList> call, Throwable t) {

            //...

        }


    });


    Log.d("onRetrieveDR", ""+ responseDogs);
    return reponseDogs;
}
}

Note ->> "Log.d("DogRESTSuccessful", "" + response.body().getDogs())" and "Log.d("dogsReceived - >", "" + responseDogs)" shows populated responseDogs...

but retrieveDogsFromREST is returning null list, and so does "Log.d("onRetrieveDR", ""+ responseDogs)"

Maybe I'm writing wrong logic? IDK

Iago Brayham
  • 509
  • 1
  • 5
  • 9
  • Populate a list with response.body() and then return it, so I can get the results and use it later. Main problem is that method is returning an empty list, but how is that possible if it's been populated inside onResponse()? – Iago Brayham Jan 09 '18 at 14:43

2 Answers2

2

You have a simple misconception in your logic. The thread to make the request is asynchronous, that means, it will eventually be executed while your application runs. Even if your request is fast it will always return null because the thread doesn't have the time to update it.

My advice to you is, make an Observer pattern once your onResponse gets called that notifies the system and trigger an event that updates the view you need to update.

Usually people end up doing something like in this post

César Ferreira
  • 681
  • 1
  • 5
  • 12
  • So, I'll try calling service.execute(...) on doInBackground inside an AsyncTask class and then updating view with onPostExecute. It might actually work. – Iago Brayham Jan 09 '18 at 14:53
  • Used rxandroid2 like in this example(https://medium.com/@mtrax/rxandroid-2-with-retrofit-2-and-gson-3f08d4c2627d) and worked perfectly! Thanks for the heads up! – Iago Brayham Jan 09 '18 at 17:40
-1

Are you sure that response body you're receiving has exactly the same structure like in your model class? Could your JSON have one upper-level object which wraps your responseDogs List? I ask that because it's hard to suppose something about this case without JSON response sample provided.

kkaun
  • 603
  • 7
  • 19