Java Realm get latest inserted item
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!