I am trying to sort RealmResults by two columns:
RealmResults<User> results = realm.where(User.class).equalTo("relevant", true).findAll();
results.sort("balance", RealmResults.SORT_ORDER_ASCENDING);
results.sort("visible", RealmResults.SORT_ORDER_ASCENDING);
setListViewData(getActivity(), results, true);
But in the listview the results are only sorted by the column visible.
So is there a way to sort by two columns?
I am using version 0.75.1.
No, currently we do not support sorting on multiple columns/fields.
Hello @zsavely.
Until proper support for multi field sorting is added to Realm, there are a few workarounds.
The most generic is to make a computed field containing both values (maybe as a string in your case), and then sort by that.
That obviously has the drawback of using more space, but only you can know if that's ok.
In your particular case it looks like one of your fields "visible" might be a boolean, and then you could sort in two steps:
RealmResults
RealmResults
results2.sort("balance", RealmResults.SORT_ORDER_ASCENDING);
Hope this helps you until we support multilevel sorting.
Cheers
For completness, this was released with 0.77.0
It would be nice if it was at least indicated in the documentation that the sort is not stable.
@njzk2 Yes we should. That is an unfortunate oversight.
@njzk2 Notice that objects in a Realm are unordered while objects in a RealmResults are ordered. The in-place RealmResults.sort() is stable (according to the classical definition: http://en.wikipedia.org/wiki/Sorting_algorithm#Stability).
To test/illustrate this, I have expanded the unit tests - please take a look at #778. We should definitely update the documentation to explain this clearly.
@kneth isn't that in contradiction with the initial report by @zsavely? Shouldn't stability inherently allow multiple successive sorts?
@njzk2 Not really. The initial report was using single field sorting twice which is sorting two different lists. After that report, we have implemented multi-field sorting.
Most helpful comment
Hello @zsavely.
Until proper support for multi field sorting is added to Realm, there are a few workarounds.
The most generic is to make a computed field containing both values (maybe as a string in your case), and then sort by that.
That obviously has the drawback of using more space, but only you can know if that's ok.
In your particular case it looks like one of your fields "visible" might be a boolean, and then you could sort in two steps:
RealmResults results = realm.where(User.class).equalTo("relevant", true).findAll(); results2 = results.where().equalTo("visible", boolean).findAll();
RealmResults
results2.sort("balance", RealmResults.SORT_ORDER_ASCENDING);
Hope this helps you until we support multilevel sorting.
Cheers