迁移工作非常繁琐,但我的应用程序在某些时候必须重新启动(recreate()
)才能进行界面操作。此时应用程序因迁移而崩溃:
java.lang.RuntimeException: Unable to start activity ComponentInfo{APP/APP.MainActivity}: java.lang.IllegalArgumentException: Configurations cannot be different if used to open the same file.
Cached configuration:
realmFolder: /data/user/0/APP/files
realmFileName : default.realm
canonicalPath: /data/data/APP/files/default.realm
key: [length: 0]
schemaVersion: 0
migration: null
deleteRealmIfMigrationNeeded: false
durability: FULL
schemaMediator: io.realm.DefaultRealmModuleMediator@19c237a3
迁移代码段:
mRealmConfig = new RealmConfiguration.Builder(this)
.schemaVersion(0)
.migration(new Migration())
.build();
realm = Realm.getInstance(mRealmConfig);
realm.close();
迁移类:
public class Migration implements RealmMigration {
@Override
public void migrate(final DynamicRealm realm, long oldVersion, long newVersion) {
RealmSchema schema = realm.getSchema();
// Migrate from version 0 to version 1
if (oldVersion == 0) {
RealmObjectSchema notificationSchema = schema.get("classTarget");
notificationSchema
.addField("something", Boolean.class, FieldAttribute.REQUIRED)
.transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
obj.set("something", true);
}
});
oldVersion++;
}
}
}
答案 0 :(得分:1)
听起来好像是多次创建RealmConfiguration实例。尝试将其保留在静态字段中或使用Realm.setDefaultInstance(config) / Realm.getDefaultInstance()
代替。
您看到异常的原因是因为您的RealmMigration类不会覆盖equals()/hashCode()
。这意味着我们的内部检查认为您有两种不同的配置,因为new Migration().equals(new Migration()) == false