I need to add auto increment key field in Realm
database in Android.
How can I do this?
Is this possible?
Thanks in advance.
I need to add auto increment key field in Realm
database in Android.
How can I do this?
Is this possible?
Thanks in advance.
Relam
currently doesn't support auto_increment
see this issue on GitHub
you can take work around like this
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
// increment index
Number num = realm.where(dbObj.class).max("id");
int nextID;
if(num == null) {
nextID = 1;
} else {
nextID = num.intValue() + 1;
}
dbObj obj = realm.createObject(dbObj.class, nextID);
// ...
}
}
The Java binding does not support primary keys yet, but it's on the roadmap and with high priority - see: https://groups.google.com/forum/#!topic/realm-java/6hFqdyoH67w . As a workaround you can use this piece of code for generating keys:
int key;
try {
key = realm.where(Child_pages.class).max("id").intValue() + 1;
} catch(ArrayIndexOutOfBoundsException ex) {
key = 0; // when there is no object in the database yet
}
I use singleton factory for generating primary keys as a more generic solution with better performance (no need to query for max("id")
every time).
There is a long discussion in Realm Git Hub if you need more context: Document how to set an auto increment id?