这个问题查询境界的数据是从一个后续问题:Organize Android Realm data in lists包含的其他对象
由于我们使用的API返回的数据,这是略不可能的境界数据库上做一个实际的查询。相反,我正在将我的订购数据包装在RealmList
中,并向其中添加@PrimaryKey public String id;
。
因此,我们的境界的数据是这样的:
public class ListPhoto extends RealmObject {
@PrimaryKey public String id;
public RealmList<Photo> list; // Photo contains String/int/boolean
}
这使得简单地使用API端点作为id
容易写入和境界DB读取。
所以它典型的查询是这样的:
realm.where(ListPhoto.class).equalTo("id", id).findFirstAsync();
这将创建一个稍微开销listening/subscribing
数据,因为现在我需要检查listUser.isLoaded()
使用ListUser
到addChangeListener/removeChangeListener
和ListUser.list
我的适配器上的实际数据。
所以我的问题是:
有没有一种方法,我可以查询这个境界接收RealmResults<Photo>
。这样我可以很容易地在RealmRecyclerViewAdapter
中使用这些数据,并直接在其上使用监听器。
编辑:为了进一步澄清,我想像下面的东西(我知道这不会编译,它只是我想实现的伪代码)。
realm
.where(ListPhoto.class)
.equalTo("id", id)
.findFirstAsync() // get a results of that photo list
.where(Photo.class)
.getField("list")
.findAllAsync(); // get the field "list" into a `RealmResults<Photo>`
编辑最终代码:考虑到它是不可能的ATM直接做的查询,我的最终解决方案是简单地有检查数据适配器,如果需要订阅。代码如下:
public abstract class RealmAdapter
<T extends RealmModel,
VH extends RecyclerView.ViewHolder>
extends RealmRecyclerViewAdapter<T, VH>
implements RealmChangeListener<RealmModel> {
public RealmAdapter(Context context, OrderedRealmCollection data, RealmObject realmObject) {
super(context, data, true);
if (data == null) {
realmObject.addChangeListener(this);
}
}
@Override public void onChange(RealmModel element) {
RealmList list = null;
try {
// accessing the `getter` from the generated class
// because it can be list of Photo, User, Album, Comment, etc
// but the field name will always be `list` so the generated will always be realmGet$list
list = (RealmList) element.getClass().getMethod("realmGet$list").invoke(element);
} catch (Exception e) {
e.printStackTrace();
}
if (list != null) {
((RealmObject) element).removeChangeListener(this);
updateData(list);
}
}
}
*有没有办法*您要查询什么我可以查询这个境界? 'realm.where(ListPhoto.class).equalTo(“id”,id).findFirstAsync();''的结果。 –
@TimCastelijns是的。我想一个'RealmResults'(甚至直接的'RealmList'),将匹配'RealmList '了'ListPhoto'内。我知道我可以通过同步呼叫来完成。但我真的更喜欢使用异步。 –
Budius
我用一些伪代码编辑了这个问题。我希望更清楚 – Budius