Deeptiman Pattnaik Deeptiman Pattnaik - 1 month ago 26x
Android Question

How do i sort Realm list alphabetically in android?

I have one realm list and i want to sort the list alphabetically.

Collections.sort(contacts, new java.util.Comparator<Contacts>() {
public int compare(Contacts l1, Contacts l2) {
String s1 = l1.getName();
String s2 = l2.getName();

return s1.compareToIgnoreCase(s2);

But this logic not woking i am posting crash report below, please kindly go through it.

java.lang.UnsupportedOperationException: Replacing and element is not supported.
at io.realm.RealmResults$RealmResultsListIterator.set(
at io.realm.RealmResults$RealmResultsListIterator.set( java.util.Collections.sort(

Please kindly go through my post and suggest me some solution.


Sorting in Realm is pretty straight forward. I don't know your RealmObject structure so I can't post the exact solution for you but here is an example

Lets assume you want to sort the contact list by name, you should sort it when your querying the results, you will get the results already sorted for you.


RealmResults<Contacts> result = realm.where(Contacts.class).findAll();
result = result.sort("name"); // for sorting ascending

// and if you want to sort in descending order
result = result.sort("name", Sort.DESCENDING);

You should go here and have a look.

Hope it helps