【发布时间】:2020-11-19 21:47:08
【问题描述】:
在 Android 上使用 Realm,我有一个自定义排序,它会抛出 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?
【问题讨论】:
-
您可以将排序设置为 RealmObject (
findAllSorted("distance", Sort.ASCENDING)) 中某个字段的排序条件,或者您需要复制所有元素。