我正在開發我的第一個應用程式,我可以在其中添加、編輯、洗掉... SQ Lite 資料庫中的物件。到目前為止,這一切都很好。使用 LiveData 加載所有存盤的物件也可以正常作業。
任何人都可以建議我,當我想從我的資料庫加載單個物件時,存盤庫中的代碼應該是什么樣子?
Dao 中的代碼如下所示:
@Query("SELECT * FROM lens_table WHERE id = :lensId LIMIT 1")
Lens getLensById(int lensId);
我在存盤庫中嘗試了這樣的簡單代碼:
public Lens getLensById(int id) {
Lens lens = lensDao.getLensById(id);
}
但這不起作用 - 我認為問題是這應該在異步任務中完成,因為我使用它來洗掉一個專案。
public void delete(Lens lens) {
new DeleteLensAsyncTask(lensDao).execute(lens);
}
private static class DeleteLensAsyncTask extends AsyncTask<Lens, Void, Void> {
private final LensDao lensDao;
private DeleteLensAsyncTask(LensDao lensDao) {
this.lensDao = lensDao;
}
@Override
protected Void doInBackground(Lens... lenses) {
lensDao.delete(lenses[0]);
return null;
}
}
這就是我開始掙扎的地方 - 存盤庫中的方法應該如何?
在活動中,分別在 ViewHolder 中,我使用的是從活動的 onCreate 方法呼叫的代碼。
public Lens getLensById(int id) {
return repository.getLensById(id);
}
非常感謝!
uj5u.com熱心網友回復:
界面
@Query("SELECT * FROM lens_table WHERE id = :lensId LIMIT 1")
LiveData<Lens> getLensById(int lensId);
回購
public LiveData<Lens> getLensById(int id) {
return lensDao.getLensById(id);
}
視圖模型
public LiveData<Lens> getLensById(int id){
return repo.getLendsById(id)
}
活動
viewModel.getLensById(id = ).observe(this,new Observer{
@Override
void onChanged(Lens lens){
//TODO()
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/375477.html
標籤:安卓 sqlite 存储库 android-room 道
上一篇:Flutter中的多對多關系
