房间数据库更改时未触发java Observer
当房间数据库更改时,我正在尝试更新RecyclerView。但是,当数据库发生更改时,不会调用MainActivity中定义的观察者的onChanged方法。如果我让DAO返回LiveData而不是列表<&燃气轮机;并在我的ViewModel中使用LiveData—它可以按预期工作。但是,我需要MutableLiveData,因为我想在运行时将查询更改为数据库
我的设置:
主要活动。java
BorrowedListViewModel viewModel = ViewModelProviders.of(this).get(BorrowedListViewModel.class);
viewModel.getItemAndPersonList().observe(MainActivity.this, new Observer<List<BorrowModel>>() {
@Override
public void onChanged(@Nullable List<BorrowModel> itemAndPeople) {
recyclerViewAdapter.addItems(itemAndPeople);
}
});
借用ListViewModel。java
public class BorrowedListViewModel extends AndroidViewModel {
private final MutableLiveData<List<BorrowModel>> itemAndPersonList;
private AppDatabase appDatabase;
public BorrowedListViewModel(Application application) {
super(application);
appDatabase = AppDatabase.getDatabase(this.getApplication());
itemAndPersonList = new MutableLiveData<>();
itemAndPersonList.setValue(appDatabase.itemAndPersonModel().getAllBorrowedItems());
}
public MutableLiveData<List<BorrowModel>> getItemAndPersonList() {
return itemAndPersonList;
}
//These two methods should trigger the onChanged method
public void deleteItem(BorrowModel bm) {
appDatabase.itemAndPersonModel().deleteBorrow(bm);
}
public void addItem(BorrowModel bm){
appDatabase.itemAndPersonModel().addBorrow(bm);
}
}
借用了DAO。java
public interface BorrowModelDao {
@Query("select * from BorrowModel")
//Using LiveData<List<BorrowModel>> here solves the problem
List<BorrowModel> getAllBorrowedItems();
@Query("select * from BorrowModel where id = :id")
BorrowModel getItembyId(String id);
@Insert(onConflict = REPLACE)
void addBorrow(BorrowModel borrowModel);
@Delete
void deleteBorrow(BorrowModel borrowModel);
}
AppDatabase。java
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase INSTANCE;
public static AppDatabase getDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE =
Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "borrow_db")
.allowMainThreadQueries()
.build();
}
return INSTANCE;
}
public static void destroyInstance() {
INSTANCE = null;
}
public abstract BorrowModelDao itemAndPersonModel();
}
共 (0) 个答案