Realm and auto increment Behavior (Android)

后端 未结 8 2128
野的像风
野的像风 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:35

    Here is a genereic solution, personnaly I create a class named RealmUtils and I add this type of methods :

     public static int getPrimaryKey(Class c)
    {
        Realm realm = Realm.getDefaultInstance();
    
        String primaryKeyFied = realm.getSchema().get(c.getSimpleName()).getPrimaryKey();
        if (realm.where(c).max(primaryKeyFied)== null)
            return 1;
        int value = realm.where(c).max(primaryKeyFied).intValue();
        return value+1;
    }
    

    Why I return 0 when the table is empty ? Because I hate Id's with 0 as value, so just change it. Hope it help someone.

提交回复
热议问题