【发布时间】:2016-07-06 09:08:00
【问题描述】:
这个问题是来自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,就可以轻松地从 Realm 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 是的。我想要一个与
ListPhoto中的RealmList<Photo>匹配的RealmResults<Photo>(甚至直接是RealmList)。我知道我可以通过同步调用来做到这一点。但我真的更喜欢使用异步。 -
我用一些伪代码编辑了这个问题。我希望它更清楚
-
我对最终的答案不是很满意,所以我需要问:一张照片可以属于多个ListPhoto吗?
-
@EpicPandaForce(史诗般的昵称),我刚刚意识到我无法以我访问的方式访问该字段。并将其删除。我仍在检查我能做什么,但它应该与你以前看到的没有太大不同。但要回答你的问题:是的。一张照片只属于一个用户,但它可以在多个相册中,在热门照片列表中,如果
orderBy是date或top,它可以在同一个相册中显示两次
标签: android realm realm-list