tux-world
tux-world

Reputation: 2720

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();
getUserLatestTransactions(Integer.parseInt(latestId));

is there any other solution or Realm has implement that?

Upvotes: 7

Views: 11030

Answers (4)

Nik
Nik

Reputation: 2060

val obj = realm.where<Transactions>()
                .sort("createdAt", Sort.DESCENDING)
                .findFirst()

if(obj != null){
   val latestId = obj.id
}

Upvotes: 1

rainmeter
rainmeter

Reputation: 31

Transactions item = realm.where(Transactions.class).findAll().last()

Note:if you want only get last insert data,no sort method

Upvotes: 3

Eenvincible
Eenvincible

Reputation: 5626

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!

UPDATE

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

That means you can simply do this:

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

Please try this and let me know!

Upvotes: 11

Md Samiul Alim Sakib
Md Samiul Alim Sakib

Reputation: 1114

If Id is unique & incremental you can sort by it or put the time as long value and do same as above it should work.

Upvotes: 0

Related Questions