Search code examples
javaandroidandroid-studionullpointerexceptionretrofit2

Null pointer exception from api response using retrofit in android studio


I have created a repository class for calling api using retrofit in android studio but I am getting null pointer exception when returning the response. Please have a look at the getUserData() method and comments in it to understand the problem better.

public class ContestRepository {

private static ApiInterface apiInterface;
private MutableLiveData<List<User>> userList;
public ContestRepository() {
    apiInterface = RetrofitService.getApiInterface();
    userList = new MutableLiveData<>();
}

public MutableLiveData<List<User>> getUserData() {
    apiInterface.getUserDetails("users").enqueue(new Callback<Root>() {
        @Override
        public void onResponse(Call<Root> call, Response<Root> response) {
            Root result = response.body();
            if(result != null) {
                String status = result.getStatus();
                System.out.println(status);
                if(status.equals("OK")) {
                    userList.setValue(result);
                    System.out.println(userList.getValue().size());  //here userList is not null
                }
            }
        }

        @Override
        public void onFailure(Call<Root> call, Throwable t) {
        }
    });
    System.out.println(userList.getValue().size());   //here is userList is null
    return userList;
}
}

As you can see in code the value of userList is not null when printed in onResponse method and when printed again before returning it the value becomes null. I don't understand why this is happening. I know this is some kind of programming mistake but I cannot figure it out. Can someone please help me?


Solution

  • System.out.println(userList.getValue().size());   //here is userList is null
    

    This is because you are printing userList before the api gives the response !!