In a table of let say 100 items, which is the best approach to get the last 20 objects.
One way I can think of is to load all the objects , reverse the array , create a new array and loop from the results for 20 times filling the new array and return it.
Something like as follows :
public ArrayList<DataObject> getLastItems (int qty){
RealmResults<DataObject>results = realm.where(DataObject.class).findAll();
Collections.reverse(results);
ArrayList<DataObject>arrayList = new ArrayList<>();
for (int i = 0; i == qty; i++){
arrayList.add(results.get(i));
}
return arrayList;
}
Is there a better faster way to do this in android using realm.io ?
Update
this is so far how this is handled..
public ArrayList<DataObject> getLastItems (int qty){
RealmResults<DataObject>results = realm.where(DataObject.class).findAll();
ArrayList<DataObject> arrayList = new ArrayList<>();
for (int i = results.size(); i > Math.max(results.size() - 20, 0) ; i--) {
arrayList.add(results.get(i-1));
}
return arrayList;
}
Also note that Realm tables are unordered. Think of them as a bag where you put your data. This means that if you want the last 20 items you inserted you will need to add a field to contain the insertion time. Doing this will also allow you to achieve the result you want very efficiently:
RealmResults<DataObject>results =
realm.where(DataObject.class)
.findAllSorted("timestamp", RealmResults.SORT_ORDER_DESCENDING);
for (int i = 0; i < 20; i++) {
// do magic here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With