[英]How to fetch the ViewModel using ViewModelProviders.of() on non-FragmentActivity?
private void subscribeToModel() {
final MyViewModel model = ViewModelProviders.of(this)
.get(MyViewModel.class);
// Update the list when the data changes
model.getItems().observe(this, new Observer<List<Item>>() {
@Override
public void onChanged(@Nullable List<Item> items) {
// Do something useful
}
});
}
This code above works well on 'AppCompatActivity' or 'FragmentActivity'. 上面的代码在“ AppCompatActivity”或“ FragmentActivity”上运行良好。 However, it does not work on another type of Activity (eg. for me: GvrActivity).
但是,它不适用于其他类型的活动(例如,对我来说:GvrActivity)。 ViewModelProviders.of() is expecting 'FragmentActivity'.
ViewModelProviders.of()预期为“ FragmentActivity”。
Is there another way to observe the DB? 还有另一种观察数据库的方法吗?
As for the DB, I am using ROOM. 至于数据库,我正在使用ROOM。
Answering my own question. 回答我自己的问题。
Observing a Room database is the solution. 解决方案是观察Room数据库。 Thanks CommonsWare.
感谢CommonsWare。
Here's full solution: 完整的解决方案:
private void subscribeToModel() {
final DatabaseCreator databaseCreator = DatabaseCreator.getInstance();
LiveData<List<Item>> itemLiveData = databaseCreator.getDatabase().itemDao().getAllLiveData();
if(itemLiveData != null) {
itemLiveData.observe(this, new Observer<List<Item>>() {
@Override
public void onChanged(@Nullable List<Item> items) {
// Do something useful
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.