tux-world tux-world - 5 months ago 149
Android Question

Java Realm get latest inserted item

In Realm database solution how can i get latest inserted item with best performance?

this code is my solution to resolve that

List<Transactions> allItems = realm.where(Transactions.class).findAll().sort("createdAt", Sort.DESCENDING);
String latestId = allItems.get(0).getId();

is there any other solution or Realm has implement that?


Here is what you could do - considering Realm reads make no copies, meaning it is not expensive and won't affect your UI thread much, after storing your item, you can findAllSorted("createdAt) or findAllSorted("id"), then find last id using last() method like this:

//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();

This should give you the last inserted ID of the given model.

It is also important to mention that for this to work, you MUST have a column in your model like this with id;

public class Transactions extends RealmObject{

   @PrimaryKey @Index
   private long id;

   //getters and setters accordingly!

I hope this helps! Good luck and happy coding!


I just realized that realm.copyToRealm(obj) returns an object!

That means you can simply do this:

Transactions transaction = realm.copyToRealm(newTransaction);
long id = transaction.getId();

Please try this and let me know!