Realm Auto Increament field example

爱⌒轻易说出口 提交于 2019-12-29 06:50: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.


回答1:


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);
         // ...
    }
}



回答2:


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?



来源:https://stackoverflow.com/questions/31229226/realm-auto-increament-field-example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!