我正在尝试运行一个采用 MVVM 模式架构的应用程序,但我遇到了一个我无法解决的异常。我有我的 MainActivity.java,它对 MainViewModel.java 中的 firstTime() 方法有一个观察。
MainActivity.java
(...)
ViewModelProvider.Factory mViewModelFactory;
ActivityMainBinding mActivityStartBinding;
private MainViewModel mainViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivityStartBinding = getViewDataBinding();
mainViewModel.firstTime().observe(this, new Observer<Boolean>() {
@Override
public void onChanged(@Nullable Boolean aBoolean) {
if(aBoolean !=null && aBoolean){
mainViewModel.setisFirstRun();
}
}
});
MainViewModel.java
(...)
private final DataManager mDataManager; <--- repository
public LiveData<Boolean> firstTime(){
if(mDataManager.isFirstRun())
{
Timber.d("-------------- Is first read from database ");
return mDataManager.saveValues();
}
else
{
Timber.d("-------------- Is not first read from database ");
return null;
}
}
每次我跑步时,我都会得到以下我无法解决的异常。
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rd.ch/com.rd.ch.ui.main.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.arch.lifecycle.LiveData.observe(android.arch.lifecycle.LifecycleOwner, android.arch.lifecycle.Observer)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.arch.lifecycle.LiveData.observe(android.arch.lifecycle.LifecycleOwner, android.arch.lifecycle.Observer)' on a null object reference
at com.rd.ch.ui.main.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:6251)
我该如何解决这个问题?