【问题标题】:Android - Get a single object from SQLite using RoomAndroid - 使用 Room 从 SQLite 获取单个对象
【发布时间】:2022-01-09 15:07:35
【问题描述】:

我正在开发我的第一个应用程序,我可以在其中添加、编辑、删除……在 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);
}

非常感谢!

【问题讨论】:

    标签: android sqlite repository android-room dao


    【解决方案1】:

    界面

    @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()
        }
    })
    

    【讨论】:

    • 谢谢!该代码对我来说很好!对这种查询也使用 LiveData 是常见的做法吗?我没有用这些信息填充回收站视图等...... LiveData 似乎是它们用于观察并立即显示变化。这可能并不总是需要。
    • 你可以使用 livedata,因为它避免了在主线程上执行请求的常见问题,你不应该这样做,但你也可以使用 rxjava 或 coroutines 之类的东西
    • @Zudy 是的。您可以使用 livedata 进行此类查询。这很简单。你也可以使用 kotlin coroutines , asynctask , rxjava 任何你想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    相关资源
    最近更新 更多