房间数据库查询 [英] Room Database Query
问题描述
我是 Room
的新手,我正在尝试 query
我的 database
以获取 row
从中.我尝试通过 querying
使用 primary key
这是 id 来这样做,但问题是我不知道如何返回目标 object
来自 repository
.
I'm new to Room
and i'm trying to query
my database
to get a row
from it. I attempted doing so by querying
it with the primary key
which is id but the problem is i don't know how to return the target object
from the repository
.
这是Dao
@Query("SELECT * FROM targets WHERE id = :id LIMIT 1")
Targets findTargetById(int id);
这是存储库类
public Targets findTarget (int id) {
new findTargetByIDAsyncTask(mTargetsDao).execute(id);
}
private static class findTargetByIDAsyncTask extends AsyncTask<Integer, Void, Targets> {
private TargetsDao mAsyncTaskDao;
findTargetByIDAsyncTask(TargetsDao dao) {
mAsyncTaskDao = dao;
}
@Override
protected Targets doInBackground(Integer... integers) {
return mAsyncTaskDao.findTargetById(integers[0]);
}
@Override
protected void onPostExecute(Targets targets) {
super.onPostExecute(targets);
}
}
推荐答案
返回结果有两种方式.
第一种方法是调用 AsyncTask.get()
方法,但如果任务超过 5 秒,它仍然会持有一个导致 ANR 的 MainThread:
The first way is to call AsyncTask.get()
method, but it will still hold a MainThread what leads to ANR if a task will longer than 5 seconds:
public Targets findTarget (int id) {
return new findTargetByIDAsyncTask(mTargetsDao).execute(id).get();
}
第二种方式更复杂,但它不会保存主线程.您应该添加一个回调类:
The second way is more complicated but it will not hold the MainThread. You should add a Callback class:
public interface Callback {
void onSuccess(Targets targets);
}
存储库中的每个方法都如下所示:
Each method of your repository will look like that:
public void findTarget (Callback callback, int id) {
new findTargetByIDAsyncTask(mTargetsDao, callback).execute(id);
}
AsynTask 看起来像这样:
And AsynTask will look like that:
private static class FindTargetByIDAsyncTask extends AsyncTask<Integer, Void, Targets> {
private final TargetsDao mAsyncTaskDao;
private final Callback callback;
FindTargetByIDAsyncTask(TargetsDao dao, Callback callback) {
mAsyncTaskDao = dao;
this.callback = callback;
}
@Override
protected Targets doInBackground(Integer... integers) {
return mAsyncTaskDao.findTargetById(integers[0]);
}
@Override
protected void onPostExecute(Targets targets) {
callback.onSuccess(targets);
}
}
这篇关于房间数据库查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!