10

I need to add auto increment key field in Realm database in Android. How can I do this? Is this possible?

Thanks in advance.

Oriol Roma
  • 329
  • 1
  • 5
  • 9
user3572524
  • 175
  • 2
  • 9

2 Answers2

14

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);
         // ...
    }
}
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
N J
  • 27,217
  • 13
  • 76
  • 96
  • Per cmelchior, "Auto-incremented keys simply do not work in a distributed setting, so it is not something we would want to provide support for in the Realm library itself." (https://github.com/realm/realm-java/pull/3875#issuecomment-265435130) – Mark McClelland Jan 16 '17 at 19:54
1

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?

zacheusz
  • 8,750
  • 3
  • 36
  • 60
  • Hi, please, Can explain How to use the singleton? I just checked the gist but I don't know how to add it in my code. – Asme Just Oct 27 '16 at 14:41
  • 1st initialize it when app starts by calling `PrimaryKeyFactory.getInstance().initialize` then you can call `PrimaryKeyFactory.getInstance().nextKey` to get next key for given class – zacheusz Oct 27 '16 at 17:36
  • So can I add `PrimaryKeyFactory.getInstance().initialize` in my Application's onCreate just once, or I should add it on any given class I want use it? – Asme Just Oct 27 '16 at 18:39
  • yeah call `initialize` in `onCreate` and then use `PrimaryKeyFactory.getInstance().nextKey` in your logic – zacheusz Nov 02 '16 at 10:26
  • Sweet kotlin code: val id = realm.where(MessageBean::class.java).max("id")?.toInt()?.plus(1) ?: 0 – Shubham AgaRwal Jan 24 '18 at 10:25