PrimaryKey'id'未由自动增量器设置

时间:2016-08-29 19:48:16

标签: primary-key realm auto-increment

我编写了一个静态类,它将RealmObject的id自动递增1。

public class AutoIncrementKey {

    public static int Next(Class<? extends RealmObject> c)
    {
        Realm realm = Realm.getDefaultInstance();
        Number maxId = realm.where(c).max("id");
        realm.close();
        if(maxId == null)
        { // no object exists, so return 0
            return 0;
        }
        return maxId.intValue() + 1;
    }

}

但是,当我像这样设置RealmObject的ID的默认值时:

@PrimaryKey private int id = AutoIncrementKey.Next(PresetSelect.class);

它永远不会奏效!特别是第一次通过realm.createObject(IExtendRealmObject.class)创建一个新类时,值为0,但AutoIncrementKey.Next(...)将id返回为1!

所以id永远不会设置为1.它始终为0,并且尝试创建更多对象会导致它抛出错误“索引已经存在:0”

是什么给出了?

正在调用AutoIncrementKey.Next()函数。它发现下一个关键是1.返回的值不是通过。

修改 所以现在我已经设法在我的Realm中创建了多个对象,我发现将id设置为默认值并不是唯一的问题。

设置使用默认值扩展RealmObject的类的任何成员是IGNORED。与此有什么关系?

1 个答案:

答案 0 :(得分:2)

那是因为而不是

to_date(%(start)s, 'YYYY-MM-DD')

你应该使用

realm.createObject(IExtendRealmObject.class) 

但我认为你的方法

realm.createObject(IExtendRealmObject.class, primaryKeyValue) 

会更稳定
public class AutoIncrementKey {

    public static int Next(Class<? extends RealmObject> c)
    {
        Realm realm = Realm.getDefaultInstance();
        Number maxId = realm.where(c).max("id");
        realm.close();
        if(maxId == null)
        { // no object exists, so return 0
            return 0;
        }
        return maxId.intValue() + 1;
    }

}

如果您在调用public class AutoIncrementKey { public static int Next(Realm realm, Class<? extends RealmModel> c) { Number maxId = realm.where(c).max("id"); if(maxId == null) { // no object exists, so return 0 return 0; } return maxId.intValue() + 1; // why not long? } } 时遇到的情况,则正在进行写入事务。

天哪,你甚至可以添加

AutoIncrementKey.Next(realm, Some.class)

它应该能够很好地满足您的需求

相关问题