领域备份和迁移到新版本

时间:2016-09-30 21:43:03

标签: android realm data-migration

我正面临一个问题,即尝试使用新的RealmObject和参数将旧的Realm结构迁移到新的结构。问题是,该应用已经在Google Play中,因此用户已将特定数据存储在某些表格中。目标是在删除领域数据库之前恢复数据并将其存储在其他位置。我现在正处于两难境地。

为了尝试解决这个问题,我在Application类上实现了以下功能:

RealmMigration migration = new RealmMigration(){
    @Override
    public void migrate(...){
        if(oldVersion == 0){
            //Get the data from realm and store somewhere else
        }
    }
}

RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
         .schemaVersion(1)
         .migration(migration)
         .deleteRealmIfMigrationNeeded()
         .build();
Realm.setDefaultConfiguration(realmConfiguration);
Realm.getInstance(realmConfiguration);

这里的问题是执行它,执行deleteRealmIfMigrationNeeded()方法并且不执行migration(),然后在我从数据库获取数据之前丢失所有数据。我想要的是,在更新应用程序时,我可以从数据库中获取版本,比较它是否为旧版本并将Realm中的数据存储在文件中,然后执行deleteRealmIfMigrationNeeded()以避免RealmMigrationNeededException。

我已经查看了以下链接:
How to backup Realm DB in Android before deleting the Realm file. Is there any way to restore the backup file?
Realm not auto-deleting database if migration needed
https://github.com/realm/realm-cocoa/issues/3583

1 个答案:

答案 0 :(得分:1)

我通过在migrate()方法中添加适当的RealmSchema解决了这个问题。类似的东西:

RealmMigration migration = new RealmMigration(){
    @Override
    public void migrate(...){
        final RealmSchema = relam.getSchema();
        if(oldVersion == 0){
            if(!schema.get("Person").getPrimaryKey().equals("codePerson")){
                schema.get("Person")
                    .removePrimaryKey()
                    .addPrimaryKey("codePerson");
            }

            //There are other similar statements here
        }
    }
}

然后我从RealmConfiguration中删除了deleteRealmIfMigrationNeeded()方法。

它解决了RealmMigrationNeededException,因此应用程序正确启动。

相关问题