问题
Given a RealmObject that has the fields latitude and longitude and you have a RealmList or a RealmResult of such objects. How do you sort by distance by for example your current Location?.
Ideas that have sprung to mind are:
- Add a field
calculatedDistance, iterate over all objects and set it. The problem with this approach is that the next time you call copyToRealmOrUpdate(..) you'll overwrite this field with null. - Call Collections.sort(...) on the list or result with my own custom Comparator but I can't find it documented anywhere the behavior of a managed RealmList or RealmResult when they're sorted by "outsiders".
- Do a really advanced query using groupings and between(..) etc - but I can't come up with a good idea.
Anyone on Android found a good solution?
回答1:
Something like this really requires Geo spatial support to work in any efficient manner.
Right now I think your best bet is copying the data out of Realm and do manual processing in a worker thread.
If you implement it in a HandlerThread you can do something like this
RealmResults<City> results = realm.where(City.class).findAllAsync();
results.addChangeListener(new RealmChangeListener<Results<City>>() {
@Override
public void onChange(RealmResults<City> cities) {
List<City> standaloneCities = realm.copyFromRealm(cities);
doManualSorting(standaloneCities);
sendToUiThread(standaloneCities);
}
});
来源:https://stackoverflow.com/questions/39733526/how-do-you-sort-a-realmlist-or-realmresult-by-distance