How to sort the list of Realm results in alphabetical order in android?

I have one list of areas and I want to sort the list alphabetically.

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

            return s1.compareToIgnoreCase(s2);
        }
 });

But this logic will not bite, I publish a crash report below, please kindly go through it.

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

Please kindly read my post and offer me some solution.

+4
source share
3 answers

Sorting in is Realmpretty simple.

Here is an example:

Suppose you want to sort your contact list by name, you must sort it when you request results, you will get results already sorted for you.

There are several ways to achieve this.

Example:

1) A simple and recommended way:

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

// sort in descending order
RealmResults<Contacts> result = realm.where(Contacts.class).findAllSorted("name", Sort.DESCENDING); 

2)

, .

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

, Realm , .

,

+15

:

RealmResults<Contacts> result = realm.where(Contacts.class)
                                     .findAllSorted("name", Sort.DESCENDING); 

findAll().sort().

+2

, SORT_ORDER_ASCENDING SORT_ORDER_DESCENDING

public void sort(java.lang.String[] fieldNames, boolean[] sortAscending) 

API 1 2

+1

Source: https://habr.com/ru/post/1653429/


All Articles