我正在使用Android架构组件,并尝试从LiveData实例化viewmodel和Observe数据,然后出现这个问题
Attempt to invoke virtual method 'void androidx.lifecycle.LiveData.observe(androidx.lifecycle.LifecycleOwner, androidx.lifecycle.Observer)' on a null object reference
这是我的调用Observe的地方,也就是报错的地方
public class CrimeListFragment extends Fragment {
private RecyclerView mRecyclerView;
private CrimeAdapter mAdapter;
private boolean mSubtitleVisible;
private LiveData<List<Crime>> mListLiveData;
private CrimeViewModel mCrimeViewModel;
//这里就只贴出了问题的区域
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_crime_list,container,false);
mRecyclerView=view.findViewById(R.id.crime_recycle_ListView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mCrimeViewModel=new ViewModelProvider(this).get(CrimeViewModel.class);
mListLiveData=mCrimeViewModel.getListLiveData();
mListLiveData.observe(this.getViewLifecycleOwner(), new Observer<List<Crime>>() {
//这里报错
@Override
public void onChanged(List<Crime> crimes) {
mAdapter.setCrimes(crimes);
updateUi();
}
});
updateUi();
return view;
}
}
这里是我Repository类和Runnable
//这个是Repository类
public class CrimeRepository {
private final CrimeDAO mCrimeDAO;
public CrimeRepository(Context context){
mCrimeDAO= CrimeDatabase.getCrimeDataBase(context).getCrimeDao();
}
public LiveData<List<Crime>> getCrimeListLive() {
MyRunnable myRunnable=new MyRunnable("SelectAllCrimeLive");
Executors.newCachedThreadPool().execute(myRunnable);
return myRunnable.getListLiveData();
}
public List<Crime> selectListCrime(){
MyRunnable myRunnable=new MyRunnable("SelectAllCrime");
Executors.newCachedThreadPool().execute(myRunnable);
return myRunnable.getCrimes();
}
//这是我自定义实现接口Runnable的类,CrimeRepository 的私有类
private class MyRunnable implements Runnable{
private LiveData<List<Crime>> mListLiveData;
@Override
public void run() {
mListLiveData=mCrimeDAO.selectAllCrimeLive();
}
}
这是我的ViewModel
public class CrimeViewModel extends ViewModel {
private final CrimeRepository mCrimeRepository;
public CrimeViewModel(@NonNull Application application){
mCrimeRepository=new CrimeRepository(application);
}
public LiveData<List<Crime>> getListLiveData(){
return mCrimeRepository.getCrimeListLive();
}
}
这是截图: