为什么即使正确设置了返回值非null,也要改造返回Null'LiveData'的方法?

时间:2020-01-16 20:36:42

标签: android android-livedata

我正确地获得了响应,正确设置了LiveData的值(将值设置为实时数据后,通过在控制台上打印值来确认)。但是,当我尝试在“返回”之前打印相同的内容时,就会出现NullPointerException。

public class ProjectRepository {

private ProjectRepository instance;
Context context;
public ProjectRepository(Context context) {
  this.context=context;
}
private MutableLiveData<List<PojoDivision>> data = new MutableLiveData<>();
public LiveData<List<PojoDivision>> getDivisionList() {
    ((RetrofitConfiguration)context).getDivisionRestApiWithAuthentication().getDivisionList().enqueue(new Callback<List<PojoDivision>>() {
        @Override
        public void onResponse(Call<List<PojoDivision>> call, Response<List<PojoDivision>> response) {

            if (response.isSuccessful()) {
                System.out.println(response.body().get(4).getName()); // this is printing

                data.setValue(response.body());
                System.out.println(data.getValue().get(4).getName()); // this is printing
            }
        }

        @Override
        public void onFailure(Call<List<PojoDivision>> call, Throwable t) {
            Log.d(TAG, t.getMessage());
        }
    });
    /*
    following code is not printing with nullPointerException
    java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
     */
    System.out.println(data.getValue().get(4).getName());
    return data;
}

}

1 个答案:

答案 0 :(得分:1)

由于您在存储库类的类级别使用LiveData对象,因此您的方法无需返回任何内容。相反,它的责任是更新该LiveData对象。

$ python3 so.py 
Which Class will you choose?: Python!
You aren't choosing a valid class.
Which Class will you choose?: Prisoner
'Never met a gen-u-ine 'Last chancer.'

此类的客户端需要1)观察LiveData对象,并2)调用public class ProjectRepository { private static final String TAG = "ProjectRepository"; private ProjectRepository instance; Context context; public ProjectRepository(Context context) { this.context = context; } public MutableLiveData<List<PojoDivision>> data = new MutableLiveData<>(); public void getDivisionList() { ((RetrofitConfiguration) context).getDivisionRestApiWithAuthentication().getDivisionList().enqueue(new Callback<List<PojoDivision>>() { @Override public void onResponse(Call<List<PojoDivision>> call, Response<List<PojoDivision>> response) { if (response.isSuccessful()) { data.postValue(response.body()); } } @Override public void onFailure(Call<List<PojoDivision>> call, Throwable t) { Log.d(TAG, t.getMessage()); } }); } } 方法以触发更新:

getDivisionList()