Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 327
Piyush Patel Avatar asked Nov 28 '22 03:11

Piyush Patel


2 Answers

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.

like image 176
EpicPandaForce Avatar answered Dec 01 '22 00:12

EpicPandaForce


You can use limit from Realm 5.6.0+. It looks like this.

val myDataList = Realm.getDefaultInstance()
    .where(MyData::class.java)
    .limit(10)
    .findAll()

Look this document

like image 26
khcpietro Avatar answered Nov 30 '22 23:11

khcpietro