Android:领域迁移问题

时间:2017-02-10 09:40:45

标签: android realm realm-migration

我是Android的新手,我在我的APP中使用了realm但是我没有指定schemaversion,现在当我想升级应用程序并实现迁移时。

以前,我这样做,

Realm.init(getApplicationContext());

RealmConfiguration realmConfiguration =
                        new RealmConfiguration.Builder().build();

realm = Realm.getInstance(realmConfiguration);

现在,

Realm.init(getApplicationContext());

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

realm = Realm.getInstance(realmConfiguration);  

而且,我收到了这个错误。

java.lang.IllegalArgumentException: Configurations cannot be different if used to open the same file. 
Cached configuration: 
realmDirectory: /data/user/0/in.avanti_app.student_companion.debug/files
realmFileName : default.realm
canonicalPath: /data/data/in.avanti_app.student_companion.debug/files/default.realm
key: [length: 0]
schemaVersion: 1
migration: in.avanti_app.student_companion.realmClasses.Migration@25
deleteRealmIfMigrationNeeded: false
durability: FULL
schemaMediator: io.realm.DefaultRealmModuleMediator@793ec9a4

New configuration: 
realmDirectory: /data/user/0/in.avanti_app.student_companion.debug/files
realmFileName : default.realm
canonicalPath: /data/data/in.avanti_app.student_companion.debug/files/default.realm
key: [length: 0]
schemaVersion: 0
migration: null
deleteRealmIfMigrationNeeded: false
durability: FULL
schemaMediator: io.realm.DefaultRealmModuleMediator@793ec9a4

我还在Migration类中覆盖hasCode和equals。

1 个答案:

答案 0 :(得分:0)

调用Realm.init(Context)初始化以下代码中的“默认配置”

public static synchronized void init(Context context) {
    if (BaseRealm.applicationContext == null) {
        if (context == null) {
            throw new IllegalArgumentException("Non-null context required.");
        }
        RealmCore.loadLibrary(context);
        defaultConfiguration = new RealmConfiguration.Builder(context).build();
        ObjectServerFacade.getSyncFacadeIfPossible().init(context);
        BaseRealm.applicationContext = context.getApplicationContext();
        SharedRealm.initialize(new File(context.getFilesDir(), ".realm.temp"));
    }
}

new RealmConfiguration.Builder(context).build();设置的配置没有架构版本,迁移,deleteIfMigrationNeeded()

要设置新的默认配置,您需要创建配置,然后调用Realm.setDefaultConfiguration(realmConfig);

RealmConfiguration realmConfiguration =
         new RealmConfiguration.Builder().schemaVersion(1).migration(new Migration()).build();
Realm.setDefaultConfiguration(realmConfiguration);
realm = Realm.getDefaultInstance();