如何使用嵌套属性对RealmList对象进行排序?
问题描述:
我已经开始使用Realm了,我很好奇如果可以通过嵌套属性对RealmList对象进行排序。如何使用嵌套属性对RealmList对象进行排序?
我有一些ListModel的对象:
public class ListModel extends RealmObject {
@Required
private String itemName;
...
private RealmList<ItemModel> items;
...
}
ItemModel是:
public class ItemModel extends RealmObject {
private TagModel tag;
...
private boolean isBought = false;
@PrimaryKey
private long created;
...
}
TagModel是:
public class TagModel extends RealmObject {
@PrimaryKey
private String tagName;
...
private CategoryModel category;
...
}
和CategoryModel是:
public class CategoryModel extends RealmObject {
@PrimaryKey
private int categoryType;
...
}
所以,我真正需要的是有这样的事情:
RealmResults<ItemModel> sortedItems= realm.where(ListModel.class)
.equalTo("created", created)
.findFirst().getItems().where().findAllSorted("isBought", Sort.ASCENDING, "tag.category.categoryType", Sort.ASCENDING, "tag.tagName", Sort.ASCENDING);
是否有可能以某种方式实现这一目标?就目前而言,据我所知,根据我的需要,不可能使用以下结构"tag.category.categoryType"
。
作为一个临时的解决方案,我想下面的办法:
ListModel listModel = realm.where(ListModel.class)
.equalTo("created", created)
.findFirst();
List<ItemModel> items = listModel.getItems();
Collections.sort(items, new Comparator<ItemModel>() {
@Override
public int compare(ItemModel lhs, ItemModel rhs) {
// here some sorting logic
}
});
,但我不知道这是一个正确的做法。
答
我有同样的问题,我解决了这个用同样的方式,使用上RealmList
集合我的某种需要字母顺序排序是嵌套在主对象的RealmList列表的名称
//medicineClassList is a RealmList with some RealmObjects
Collections.sort(medicineClassList, new Comparator<MedicineClass>() {
@Override
public int compare(MedicineClass lmo, MedicineClass rmo) {
String lmo_string = lmo.getProduct_request().getProduct().getName();
String rmo_string = rmo.getProduct_request().getProduct().getName();
return lmo_string.compareToIgnoreCase(rmo_string);
}
});
于是我用medicineClassList
在自定义适配器设置的ListView这里我把结果
希望这有助于。
答
贡萨洛的方法现在看起来不错。但是由于访问嵌套的项目会导致I/O,所以速度很慢。 在我的情况下,10000个物品需要约30秒。 所以我将其改进为使用缓存。
Collections.sort(medicineClassList, new Comparator<MedicineClass>() {
Map<String, String> primaryKey2SortKey = new HashMap();
@Override
public int compare(MedicineClass lmo, MedicineClass rmo) {
String lmo_string = pullSortKey(lmo);
String rmo_string = pullSortKey(rmo);
return lmo_string.compareToIgnoreCase(rmo_string);
}
private String pullSortKey(MedicineClass item) {
if (primaryKey2SortKey.containsKey(item.getPrimaryKey())) {
return primaryKey2SortKey.get(item.getPrimaryKey());
}
String sortKey = item.getProduct_request().getProduct().getName();
primaryKey2SortKey.put(item.getPrimaryKey(), sortKey);
return sortKey;
}
});
对不起,境界不支持孩子的财产排序,现在:(见https://github.com/realm/realm-java/issues/709,你的副作用临时解决方案是排序需要在Realm事务中运行,并且在Realm中实际的'RealmList''项目将在排序后被更改。也许你想要创建一个新的集合并对其进行排序。 – beeender