0

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?

2
  • You are getting your response in background, and you are returning your userLits before you get your data. Commented Jan 23, 2022 at 6:07
  • You can use coroutine or flow to solve this kinds of issue Commented Jan 23, 2022 at 6:08

1 Answer 1

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

can you please tell me what is the appropriate way to return the list in the method?
get Your data when api gives response as success .
I used userList.postvalue() instead of .setValue() and it worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.