[英]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. 请查看 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;
}
}
正如您在代码中看到的,在 onResponse 方法中打印时 userList 的值不是 null 并且在返回之前再次打印时,值变为 null。 我不明白为什么会这样。 我知道这是某种编程错误,但我无法弄清楚。 有人可以帮帮我吗?
System.out.println(userList.getValue().size()); //here is userList is null
这是因为您在 api 给出响应之前打印 userList !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.