简体   繁体   English

Null 指针异常来自 api 响应在 android 工作室中使用 retrofit

[英]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. 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.请查看 getUserData() 方法和其中的注释以更好地理解问题。

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.正如您在代码中看到的,在 onResponse 方法中打印时 userList 的值不是 null 并且在返回之前再次打印时,值变为 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?有人可以帮帮我吗?

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

This is because you are printing userList before the api gives the response !!这是因为您在 api 给出响应之前打印 userList !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM