Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm.io Android best approach to get last 20 items from a table

Tags:

android

realm

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;
}
like image 363
J.Vassallo Avatar asked Jan 30 '15 05:01

J.Vassallo


1 Answers

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
}
like image 147
Emanuelez Avatar answered Oct 16 '22 11:10

Emanuelez