Java Realm获取最新插入的项目

tux*_*rld 6 java android realm

在Realm数据库解决方案中,如何获得性能最佳的最新插入项?

这段代码是我解决这个问题的解决方案

List<Transactions> allItems = realm.where(Transactions.class).findAll().sort("createdAt", Sort.DESCENDING);
String             latestId = allItems.get(0).getId();
getUserLatestTransactions(Integer.parseInt(latestId));
Run Code Online (Sandbox Code Playgroud)

还有其他解决方案或Realm实现了吗?

Een*_*ble 11

这是你可以做的 - 考虑到Realm读取没有副本,这意味着它不贵并且不会影响你的UI线程,在存储你的项目之后,你可以findAllSorted("createdAt)或者findAllSorted("id"),然后使用这样的last()方法找到最后的id :

//after commitTransaction, 

RealmResults<Transactions> allTransactions = realm.where(Transactions.class).findAllSorted("createdAt");

//If you have an incrementing id column, do this
long lastInsertedId = allTransactions.last().getId();
Run Code Online (Sandbox Code Playgroud)

这应该为您提供给定模型的最后插入ID.

同样重要的是要提到这一点,你必须在你的模型中有一个像id这样的列;

public class Transactions extends RealmObject{

   @PrimaryKey @Index
   private long id;

   //getters and setters accordingly!
}
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!祝你好运,编码愉快!

UPDATE

我刚刚意识到realm.copyToRealm(obj)返回一个对象!

这意味着你可以简单地这样做:

realm.beginTransaction();
Transactions transaction = realm.copyToRealm(newTransaction);
long id = transaction.getId();
realm.commitTransaction();
Run Code Online (Sandbox Code Playgroud)

请试试这个让我知道!