简体   繁体   English

Android - 使用 Room 从 SQLite 获取单个 object

[英]Android - Get a single object from SQLite using Room

I am working on my first app where I can add, edit, delete,... objects in a SQ Lite database.我正在开发我的第一个应用程序,我可以在其中添加、编辑、删除……在 SQ Lite 数据库中的对象。 This all works fine so far.到目前为止,这一切都很好。 Also loading all stored objects with LiveData works fine.使用 LiveData 加载所有存储的对象也可以正常工作。

Can anybody advice me, how the code in the repository should look like, when I want to load a single object from my database?当我想从我的数据库中加载单个 object 时,任何人都可以建议我,存储库中的代码应该是什么样子?

The code in the Dao looks like that: Dao 中的代码如下所示:

@Query("SELECT * FROM lens_table WHERE id = :lensId LIMIT 1")
Lens getLensById(int lensId);

I tried with a simple code like this in the repository:我尝试在存储库中使用这样的简单代码:

public Lens getLensById(int id) {
    Lens lens = lensDao.getLensById(id);
}

But that does not work - I assume the problem is that this should be done in an Asynchronous Task as I use it for deleting an item.但这不起作用 - 我认为问题是这应该在异步任务中完成,因为我使用它来删除项目。

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;
    }
} 

And there is where I begin to struggle - how should the methods look like in the repository?这就是我开始挣扎的地方——存储库中的方法应该是什么样子?

In the activity, respectively in the ViewHolder I am using this code which is called from the onCreate method of the activity.在活动中,分别在 ViewHolder 中,我使用从活动的 onCreate 方法调用的这段代码。

public Lens getLensById(int id) {
    return repository.getLensById(id);
}

Thank you so much!太感谢了!

interface界面

@Query("SELECT * FROM lens_table WHERE id = :lensId LIMIT 1")
LiveData<Lens> getLensById(int lensId);

repo回购

public LiveData<Lens> getLensById(int id) {
    return lensDao.getLensById(id);
}

ViewModel视图模型

public LiveData<Lens> getLensById(int id){
    return repo.getLendsById(id)
}

Activity活动

viewModel.getLensById(id = ).observe(this,new Observer{
    @Override 
    void onChanged(Lens lens){
        //TODO()
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM