我正确地获得了响应,正确设置了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;
}
}
由于您在存储库类的类级别使用LiveData对象,因此您的方法无需返回任何内容。相反,它的责任是更新该LiveData对象。
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());
}
});
}
}
此类的客户端需要1)观察LiveData对象,以及2)调用该getDivisionList()方法以触发更新:
class MyFragment extends Fragment {
private ProjectRepository repository;
private void setRepository() {
Context context = getContext();
if (context == null) return;
repository = new ProjectRepository(context);
}
public void observeData() {
repository.data.observe(this, new Observer<List<PojoDivision>>() {
@Override
public void onChanged(List<PojoDivision> pojoDivisions) {
// do something with updated data
}
});
}
public void triggerUpdate() {
repository.getDivisionList();
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。