Reputation: 325
How I can select first N element from Realm database. Now,I use this code to select N elements:
Realm.getDefaultInstance()
.where(MyObject.class)
.findAllSorted("myField", Sort.DESCENDING)
But this select operation is too long. I need to SQL 'LIMIT' operation analog.
Upvotes: 2
Views: 8699
Reputation: 4108
I did that using limit method, You should use latest version classpath "io.realm:realm-gradle-plugin:5.8.0"
RealmResults<YourPOJOClass> realmResults = mRealm.where(YourPOJOClass.class).sort("createdTime").limit(10).findAll();
//here this record will be sorted by ascending order using schema name "createdTime"
//this will return the 10 rows only.
`
Upvotes: 2
Reputation: 5962
Possible duplicate Since I already posted the solution here : Limit Realm results
I figured out the solution to achieve this after so many days using "between" query as found in the official docs https://realm.io/docs/java/latest
If you want to fetch first N elements, Simply pass the count from and to with field name as below
realm.where(clazz).between("count",0,1000).findAll();
Where,
"count" = Field name (i.e variable name in your pojo)
"0" = Range From
"1000" = Range to
For example: The above query will fetch first 0 to 1000 as RealmResults.
Note: The above solution works only if you have some unique id with row count. In my case I manually inserted count value before inserting the values into Realm.
Upvotes: 0
Reputation: 3324
Simple
int N=10; // whatever value you want
Realm mRealm=Realm.getDefaultInstance();
RealmResults<Example> list= mRealm.where(Example.class).findAll();
list.subList(0,N);
Upvotes: 2
Reputation: 71
You can have a look at this https://github.com/realm/realm-java/issues/544
seems realm results are lazy loaded so you dun need "limit" when using realm
Upvotes: 3