我想做一次迁移(Realm 87.2),我之前也做过其他的,但这一次并不容易,我不知道为什么
我的预先分类.class
private int code;
private String title;
private String category;
private int order;
private boolean visible;
新的 Category.class
@PrimaryKey @Index private String id;
private int code;
private String title;
private String category;
private int order;
private boolean visible;
以及 Migration.class
public class Migration....
int i = 0;
.....
if(oldVersion == 7) {
schema.get("Category").addField("id", String.class, FieldAttribute.PRIMARY_KEY).transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
obj.set("id", UtilsForAll.getRandomUUID()); //Get Random UUID for previsoly added categories
obj.set("order", i);
i++;
}
});
oldVersion++;
}
} //finishClass
出于某种愚蠢的原因,我不知道我做错了什么,它一直给我这个错误:
java.lang.IllegalArgumentException: Illegal Argument: Field "id" cannot be a primary key, it already contains duplicate values:
什么?我很确定,类别类中没有重复的值。
PS:当我真正使用迁移并且有以前的类别记录时,就会发生这种情况
--------------------- 编辑 22/03
尝试了 Emanuelez 的建议:
if(oldVersion == 7) {
schema.get("Category").addField("id", String.class);
schema.get("Category").transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
obj.set("id", UtilsForAll.getRandomUUID()); //Get Random UUID for previsoly added categories
}
});
oldVersion++;
schema.get("Category").setPrimaryKey("id");
}
错误变成了这个 -
io.realm.exceptions.RealmMigrationNeededException: Field 'id' does support null values in the existing Realm file. Remove @Required or @PrimaryKey from field 'id' or migrate using io.realm.internal.Table.convertColumnToNotNullable().
我已经尝试过
.setNullable("id", true);`
也没有改变
最佳答案
要添加新的主键字段,您不能只添加具有该属性的字段,因为所有这些字段都将初始化为其默认值,全部相等,这会破坏主键契约。
要以正确的方式做到这一点,您必须:
- 创建一个新字段
- 使用新的不同值填充新字段
- 将新字段设为主键
为了进一步引用,我建议您查看 RealmObjectSchema 类的单元测试,可以在 here 中找到它。
关于java - Realm 迁移重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36146860/