有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java领域迁移重复的值

我想做一个迁移(领域87.2),我以前做过其他迁移,但这次不容易,我不知道为什么

我以前的观点是绝对的。阶级

private int code;
private String title;
private String category;
private int order;
private boolean visible;

新类别。班级

@PrimaryKey @Index private String id;
    private int code;
    private String title;
    private String category;
    private int order;
    private boolean visible;

在移民大会上。阶级

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:

什么?我敢肯定,Category类中没有重复的值

PS:当我真的使用迁移并且有以前的类别记录时,就会发生这种情况

---------编辑2003年12月22日

按照埃马努埃雷斯的建议尝试:

  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().

ve tried。setNullable(“id”,true);`

也没什么变化


共 (1) 个答案

  1. # 1 楼答案

    要添加一个新的主键字段,您不能只添加一个具有该属性的字段,因为所有这些字段都将被初始化为默认值,即所有字段都相等,这会破坏主键契约

    要以正确的方式做到这一点,你必须:

    1. 创建一个新字段
    2. 用新的不同值填充新字段
    3. 将新字段设为主键

    为了进一步参考,我建议您查看RealmObjectSchema类的单元测试,可以在here