How do i sort Realm Results list alphabetically in android?

Use this to get the sorting in SORT_ORDER_ASCENDING or SORT_ORDER_DESCENDING

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

Check the API reference Reference 1 or Reference 2


Technically you should use the following:

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

It is recommended over findAll().sort().


Sorting in Realm is pretty straight forward.

Here is an example:

Let's 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.

There are multiple ways to achieve this

Example:

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

Updated since realm 5.0.0

1) Simple and Recommended way:

// for sorting ascending, Note that the Sort.ASCENDING value is the default if you don't specify the order
RealmResults<Contacts> result = realm.where(Contacts.class).sort("name").findAll();

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

2) for unsorted results

If you are getting unsorted results you can sort them anywhere this way.

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

Have a look here you will find very detailed examples about Realm querying, sorting and other useful usage.

Tags:

Android

Realm