Realm and auto increment Behavior (Android)

后端 未结 8 2125
野的像风
野的像风 2020-12-14 16:22

I\'m trying to get data from Realm using an ID as a reference. However, when querying for an ID, I\'ve found that Realm is giving me the same ID for all elements (ID of 0).

8条回答
  •  盖世英雄少女心
    2020-12-14 16:46

    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;
    }
    

    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 thanks to AtomicInteger).

    There is a long discussion in Realm Git Hub if you need more context: Document how to set an auto increment id?

提交回复
热议问题