Piyush Patel Piyush Patel - 2 months ago 12
Android Question

How can I set LIMIT in query in Realm?

I have done R&D for limit in query with no success. There is one way with which to paginate data in

with sub list but no success with that. It shows duplicate value in it.

Here is what I attempted for pagination.

RealmResults<Person> mPersonData=RealmUtils.getAllPersonWithTagsDescending();
if (mPersonData != null) {
int startPos=getAllPerson.size()-1;
int endPos=mPersonData.size()-1;
List<Person> newPersonData=mPersonData.subList(startPos,endPos);

What am I doing wrong?


There is no reason to use pagination with Realm if you use RealmResults<T> directly, because the elements in RealmResults are lazy evaluated, and aren't in memory until you call .get(i).

Meaning, the query doesn't execute and evaluate an element until you directly index it. Which means, they aren't in memory. The RealmResults<T> list doesn't actually contain the elements, it just knows how to find them.

As such, there is no LIMIT in Realm.

Please note that if I remember correctly, reevaluating two RealmResults that are not returned by findAllSorted can have different ordering (if deletions occur). If the order must be the same no matter what, then consider a rank property, and order by findAllSorted("rank", Sort.ASCENDING).

If you really want pagination, you should have the rank parameters, and then you can create a query like

     .greaterThanOrEqualTo("rank", pageSize*pageIndex + 0)
     .lessThan(SomeClassFields.RANK, pageSize*pageIndex + pageSize)
     .findAllSorted(SomeClassFields.RANK, Sort.ASCENDING);

Also, you should consider using RealmRecyclerViewAdapter instead from here:

compile 'io.realm:android-adapters:1.3.0'

The RealmRecyclerViewAdapter handles "loading the new data" for you, you don't have to do anything to make it work beyond setting the initial RealmResults.