api 响应中的空指针异常在 android studio 中使用改造

Null pointer exception from api response using retrofit in android studio

我已经创建了一个存储库 class,用于在 android studio 中使用改造调用 api,但是在返回响应时出现空指针异常。请查看 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 的值不为空,并且 在返回之前再次打印时,该值变为空值。 我不明白为什么会这样。我知道这是某种编程错误,但我无法弄清楚。有人可以帮我吗?

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

这是因为您在 api 给出响应之前打印 userList !!