使用Realm for Android我有一个自定义排序会抛出java.lang.UnsupportedOperationException:不支持替换和元素
所以,我有一段数据需要在我从Realm数据库中检索后进行排序,所以它就像这样坐在List集合中:
Collections.sort(stores, new DistanceComparator(currentLocation));
DistanceComparator如下所示:
public class DistanceComparator implements Comparator<Restaurant> {
private Location currentLocation;
public DistanceComparator(Location location) {
currentLocation = location;
}
public int compare(RealmObject c1, RealmObject c2) {
if ((LocationUtil.calculateSomeValue(c1.getLocation()))
== (LocationUtil.calculateSomeValue(c2.getLocation()))) {
return 0;
}
else if ((LocationUtil.calculateSomeValue(c1.getLocation()))
< (LocationUtil.calculateSomeValue(c2.getLocation()))) {
return -1;
}
else {
return 1;
}
}
}
然而,当我执行排序时,我得到了一个:
java.lang.UnsupportedOperationException: Replacing and element is not supported.
at io.realm.RealmResults$RealmResultsListIterator.set(RealmResults.java:868)
at io.realm.RealmResults$RealmResultsListIterator.set(RealmResults.java:799)
at java.util.Collections.sort(Collections.java:247)
由于数据的瞬态特性,我无法在Realm中执行排序。
您是否可以对碰巧拥有Realm数据的集合执行基本排序,还是需要在RealmObject类中添加某种注释才能执行此类排序?
我确实看过这个问题,如果这不起作用,那就是我的后备:How do you sort a RealmList or RealmResult by distance?
答案 0 :(得分:1)
您无法在RealmResult
上执行自定义排序。您必须将结果复制到非托管List
并使用它而不是领域结果。
List<ModelMyFlirtsItem> storesList = realm.copyFromRealm(stores);
Collections.sort(storesList, new DistanceComparator(currentLocation));
答案 1 :(得分:0)
您可以考虑将LocationUtil
评估的值移动到RealmObject本身,并按Realm进行排序。
public int compare(RealmObject c1, RealmObject c2) {
if ((LocationUtil.calculateSomeValue(c1.getLocation()))
== (LocationUtil.calculateSomeValue(c2.getLocation()))) {
return 0;
}
else if ((LocationUtil.calculateSomeValue(c1.getLocation()))
< (LocationUtil.calculateSomeValue(c2.getLocation()))) {
return -1;
}
else {
return 1;
}
}
可能是
public class RealmObject extends RealmObject {
private Integer distance;
private Location location;
public void setLocation(Location location) {
if(location == null) {
this.distance = null;
} else {
this.distance = LocationUtil.calculateSomeValue(location);
}
this.location = location;
}
}
然后
RealmResults<RealmObject> results = realm.where(RealmObject.class).findAllSorted("distance", Sort.ASCENDING);
答案 2 :(得分:0)
在RealmResults
中使用排序,我也遇到了这个问题。我仅使用Realm
的本机.sort()
函数解决了该问题。例如-
RealmResult<Location> stores......;
.......
.......
stores.sort(new DistanceComparator(currentLocation));