Realm and auto increment Behavior (Android)

Bachlet Tansime picture Bachlet Tansime · May 4, 2015 · Viewed 21.5k times · Source

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). Why doesn't the ID auto-increment when I use the @PrimaryKey annotation on the model's ID?

Here's the shortened class for the model:

public class Child_pages extends RealmObject {
    @PrimaryKey
    private int id_cp;

    private int id;
    private String day;
    private int category_id;

And the query I'm executing is: realm.where(Child_pages.class).equalTo("id_cp",page_id).findFirst()

Answer

Bachlet Tansime picture Bachlet Tansime · May 4, 2015

Realm currently doesn't support auto incrementing primary keys. However you can easily implement it yourself using something like:

public int getNextKey() { 
    try { 
         Number number = realm.where(object).max("id");
         if (number != null) {
             return number.intValue() + 1;
         } else {
             return 0;
         }
    } catch (ArrayIndexOutOfBoundsException e) { 
         return 0;
    }
}

I hope that can get you started.