How do you sort a RealmList or RealmResult by distance?

这一生的挚爱 提交于 2019-12-11 02:24:57

问题


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:

  1. 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.
  2. 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".
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!