Reputation: 12300
How can I make sure a RealmResult
is sorted based on the sort order of an ids integer array?
public static RealmResults<ContentPage> getContentPages(Realm realm, Integer[] ids) {
return realm.where(ContentPage.class)
.in(ContentPage.FIELD_ID, ids).findAll();
}
So I am looking for a way to sort the ContentPage
objects, based on their id location in the ids array.
I am not converting this RealmResult
to a list, it is an auto managed object and so I cannot run a normal Comparator
on it after retrieval.
*EDIT: If I try to use a normal comparator on a RealmResult, I'll get: UnsupportedOperationException: Replacing and element is not supported.
*EDIT 2: My questions seems to be unclear: If I have an ids array like this: [3,1,2]
. That goes into .in(ContentPage.FIELD_ID, ids)
above. I would like the RealmResult to be in that order: item with id 3 first, 1 after that, 2 last.
*EDIT 3: Fixed by creating a new ArrayList from the RealmResult every time it changes (use a Realm ChangeListener) and using that further in my app. You can sort this copied array. Not ideal, but a temporary solution.
List copiedList = new ArrayList<>(getPagesResult);
Collections.sort(copiedList, comparator);
Upvotes: 3
Views: 1036
Reputation: 12300
Conclusion: It is not supported by Realm.
One can fix this by creating a new ArrayList
from the RealmResult
every time it changes (use a RealmChangeListener
) and using that in the app. You can sort this copied array. Not ideal, but a working solution.
List copiedList = new ArrayList<>(getPagesResult);
Collections.sort(copiedList, comparator);
If you are using a RealmRecyclerViewAdapter
this won't work though, you need the RealmResult
for that. Also, this solution takes away other niceties of using RealmResults
.
Upvotes: 2
Reputation: 3007
You can replace findAll();
with findAllSorted();
at the end of your query`
.findAllSorted(ContentPage.FIELD_ID, Sort.ASCENDING);
Upvotes: 0
Reputation: 2486
just use findAllSorted:
return realm.where(ContentPage.class)
.in(ContentPage.FIELD_ID, ids).findAllSorted("id",Sort.DESCENDING);
Upvotes: 0