I need to add auto increment key field in Realm
database in android.
how can i do this?
Is this possible?
Thanks in advance.
Auto-incrementing keys has been a much often requested feature, but at the moment, it’s not offered as a feature in Realm. That being said, if it’s something you want, it’s very easy to implement yourself in Realm as it’s really only a matter of querying for the latest object in the database, and incrementing its key by 1.
1) Create custom entity i.e. “Auto Number” Entity with fields “Seed Value” ,” Next Number” etc. Create one record of this entity with Seed Value=1 and Next Number=0 2) Create custom entity i.e. “Auto Number Locker” entity . Create one record of this record. 3) Develop a plugin which will set auto incremental field. In plugin follow below steps:
AUTO INCREMENT Field. Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.
The following SQL statement defines the "Personid" column to be an auto-increment primary key field in the "Persons" table: ); The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.
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);
// ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With