Sadly, I can't comment on other answers, but I'd like to add to Vinicius` answer.
First, you shouldn't open a new realm instance, when looking for primary key, especially when you don't close them, as this adds to maximum possible file descriptor count.
Secondly, although this is a preference, you shouldn't have primitive types (or object equivalents) as nullables (in Kotlin), as this adds redundant requirement to check nullability.
Third, since you're using kotlin, you can just define an extension method to Realm
class, such as:
fun Realm.getNextId(model: RealmModel, idField : String) : Long
{
val count = realm.where(model::class.java).max(idField)
return count + 1L
}
Since all RealmObject
instances are RealmModel
, and even objects that aren't tracked by Realm are still RealmModel
instances, therefore it will be available where ever you use your realm related classes. Java equivalent would be:
static long getNextId(RealmModel object, Realm realm, String idField)
{
long count = realm.where(object.class).max(idField);
return count + 1;
}
Late edit note: You're better off not using this approach if you're dealing with data that might come from outside sources, such as other databases or the web, because that WILL result in collisions between data in your internal database. Instead you should use max([id field name])
. See the previous snippets, I already modified them to accommodate for this edit.