How can I set LIMIT in query in Realm?

Piyush Patel picture Piyush Patel · Aug 10, 2016 · Viewed 15.2k times · Source

I have done R&D for limit in query with no success. There is one way with which to paginate data in Realm 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);   
    getAllPerson.addAll(newPersonData); 
    mAdapter.notifyDataSetChanged(); 
}

What am I doing wrong?

Answer

EpicPandaForce picture EpicPandaForce · Aug 10, 2016

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

realm.where(SomeClass.class)
     .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' // for Realm 0.89.0 to Realm 2.3.0

or

compile 'io.realm:android-adapters:2.1.0' // for Realm 3.0.0+    

or

compile 'io.realm:android-adapters:3.0.0' // for Realm 5.0.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.



I'll actually have to change this answer once there is proper integration with the Paging Architecture Component, who knew? I have an experiment up with it here and you can see if it works for you.