Search code examples
androidrealm

Realm Android: order by id-list


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);

Solution

  • 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.