kulikovman
kulikovman

Reputation: 401

How sort by date in RealmResults

There are fields for storing the date. Some fields have a date, and some fields are empty (without a date). I need to sort in such a way that at the beginning of the list there are fields with a date in ascending order. And at the end of the list, there were fields without a date.

A normal sort places the fields without a date at the top of the list.

RealmResults<Task> results = mRealm.where(Task.class).findAll()
                .sort(Task.TARGET_DATE, Sort.ASCENDING);

How can I arrange sorting so that the fields without a date are at the end of the list?

Upvotes: 2

Views: 532

Answers (1)

Tomas Ivan
Tomas Ivan

Reputation: 2320

Realm currently (v4.2.0) don't supports feature to specify where will be NULL values placed (beginning/end).

Only way how you can achieve this, is create two separate Realm Queries. Take a look at similar answer here.

//sorted result without date equal null
RealmResults<Task> results_sorted = mRealm
            .where(Task.class)
            .isNotNull(Task.TARGET_DATE)
            .findAll()
            .sort(Task.TARGET_DATE, Sort.ASCENDING);

//result containing only Tasks with null date
RealmResults<Task> results_null = mRealm
            .where(Task.class)
            .isNull(Task.TARGET_DATE)
            .findAll();

Then you can merge result to unmanageable List<Task> or wrap them to List<RealmResults<Task>> and attach listener for each result set.

Upvotes: 0

Related Questions