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

我与影子孤独终老i 提交于 2019-12-04 05:48:57

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
}

This question has been almost closed, but I found another way to figure out that situation, I don't know if is the best option or a good practice, @ChristianMelchior can say better than me about that (I saw your collaboration with realm project)... well, codes say more than words.

RealmResults<Appointment> appointments; 
List<Appointment> appointments = appointments.subList(0, appointments.size());

As we can see, answering your question Johan, you can just change the index to get all objects that you want!

RealmResults only create objects you actually use, so iterating over all of them to reverse the list would be really bad performance wise. Instead as bmunk described, you should just find the proper index and start from there, like the below. Note that Realms are unordered so without a sort, the items returned would not be well defined.

public ArrayList<DataObject> getLastItems (int qty){
    RealmResults<DataObject>results = realm.where(DataObject.class).findAll().sort("fieldName");
    ArrayList<DataObject> arrayList = new ArrayList<>();
    for (int i = Math.max(result.size() - 20, 0); i < results.size() ; i++) {
        arrayList.add(results.get(i));
    }

    return arrayList;
}

Do like this

Realm mRealm=Realm.getDefaultInstance();

RealmResults<Example> list= mRealm.where(Example.class).findAll();
list.subList(list.size()-20,list.size());

You should try to avoid copying objects unless strictly needed. Once you have done a findAll() you already got an ordered list. You could then just use max(results.size()-20, 0) to know which index to start your iteration from instead of copying.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!