领域无法迁移

时间:2016-07-31 14:09:40

标签: android android-studio realm realm-migration

我有一个我想要应用迁移的Realm模型。但是,当我应用迁移时,我收到错误

Configurations cannot be different if used to open the same file. 
The most likely cause is that equals() and hashCode() are not overridden in the migration class: 

在我的Activity类中,配置设置为:

realmConfiguration = new RealmConfiguration
                .Builder(this)
                .schemaVersion(0)
                .migration(new Migration())
                .build();

我使用realm实例来获取一些值。然后我使用以下方法应用迁移:

RealmConfiguration config = new RealmConfiguration.Builder(this)
            .schemaVersion(1) // Must be bumped when the schema changes
            .migration(new Migration()) // Migration to run
            .build();

Realm.setDefaultConfiguration(config);

当我这样称呼时:realm = Realm.getDefaultInstance();我收到上述错误。我正确应用迁移吗?

5 个答案:

答案 0 :(得分:4)

您的迁移应如下所示:

public class MyMigration implements Migration {
    //... migration

    public int hashCode() {
       return MyMigration.class.hashCode();
    }

    public boolean equals(Object object) {
       if(object == null) { 
           return false; 
       }
       return object instanceof MyMigration;
    }
}

答案 1 :(得分:1)

您是否尝试在equals课程中覆盖hashcodeMigration作为例外消息?

The most likely cause is that equals() and hashCode() are not overridden in the migration class

答案 2 :(得分:0)

覆盖Migration类中的equals和hashcode方法,如下所示:

@Override
public boolean equals(Object obj) {
    return obj != null && obj instanceof Migration; // obj instance of your Migration class name, here My class is Migration.
}

@Override
public int hashCode() {
    return Migration.class.hashCode();
}

答案 3 :(得分:0)

我认为问题是信息的第一部分 “如果用于打开同一个文件,配置不能有所不同。”您正在使用两种不同的配置来打开领域。您的一个示例使用schemaVersion 0,另一个使用schemaVersion 1.您应该在整个应用程序中使用相同的版本。

每当您需要新数据迁移时,请提升架构版本号,并在类迁移中添加代码,以查看旧/新架构版本并执行适当的迁移。

答案 4 :(得分:-1)

将模式版本添加为MyMigration中的字段,覆盖等于():

    private final int version;

    @Override
    public boolean equals(Object o) {
        return this.version == ((MyMigration)o).version;
    }

    public MyMigration(int version) {
        this.version = version;
    }
相关问题