簡體   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. 請查看 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM