当我的应用程序运行时,StartFragment 在我的 Room DB 上运行 LiveData 查询以获取 PersonId。第一次数据库调用似乎创建/打开数据库,但 LiveData onChanged() 从未被调用,然后 StartFragment 和 StartActivity 都被销毁。但是在 LogCat 中解释这个没有错误。应用程序自动重启并按预期运行,查询将值返回给 onChanged()。在我的 LogCat 的输出之下。
StartActivity onCreate()
StartFragment onCreate()
StartFragment onCreateView()
StartFragment onStart()
StartFragment queryPersonId()
StartFragmentViewModel queryPersonId_LD()
MyAppDatabase getDatabase()
MyAppDatabase getDatabase() Creating new DB instance...
MyAppDatabase DB INSTANCE not null
MyAppDatabase onOpen()
StartFragment onDestroyView() <=== why does this happen?
StartFragment onDestroy()
StartActivity onDestroy()
...
app restarts
...
StartActivity onCreate()
StartFragment onCreate()
StartFragment onCreateView()
StartFragment onStart()
StartFragment queryPersonId()
StartFragmentViewModel queryPersonId_LD()
MyAppDatabase getDatabase() <=== DB instance already created and opened
StartFragment queryPersonId().onChanged(), personId = 1 <== why don't come here above?
...
我的代码如下:
StartFragment.class
private void queryPersonId() {
mViewModel.queryPersonId_LD().observe(getViewLifecycleOwner(), new Observer<Long>() {
@Override
public void onChanged(@Nullable Long personId) {
// Don't come here first time, but do second time.
});
}
}
StartFragmentViewModel.class
public LiveData<Long> queryPersonId_LD() {
MyRepo repo = new MyRepo(getApplication());
return repo.getPersonId();
}
MyRepo.class
public MyRepo(Application application) {
super();
MyAppDatabase db = MyAppDatabase.getDatabase(application);
dao = db.getPersonIdDao();
}
public LiveData<Long> getPersonId() {
return dao.getPersonId();
}
MyAppDatabase.class
if (DB_INSTANCE == null) {
synchronized (MyAppDatabase.class) {
if (DB_INSTANCE == null) {
LogUtil.msg("getDatabase() Creating new DB instance...");
DB_INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
MyAppDatabase.class, Constants.DB_NAME)
.addCallback(rdc)
.build();
}
}
}