Realm.io Android从表中获取最后20个项目的最佳方法 [英] Realm.io Android best approach to get last 20 items from a table

查看:66
本文介绍了Realm.io Android从表中获取最后20个项目的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个可以说100个项目的表中,这是获取最后20个对象的最佳方法.

In a table of let say 100 items, which is the best approach to get the last 20 objects.

我能想到的一种方法是加载所有对象,反转数组,创建新数组并根据结果循环20次,以填充新数组并将其返回.

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.

如下所示:

 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;
}

在Android中使用realm.io有更好的方法吗?

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;
}

推荐答案

还要注意,Realm表是无序的.将它们视为存放数据的包.这意味着,如果要插入的最后20个项目,则需要添加一个字段以包含插入时间.这样做还可以使您非常有效地获得所需的结果:

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
}

这篇关于Realm.io Android从表中获取最后20个项目的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆