【问题标题】:Realm Backup and Migration to a new version领域备份和迁移到新版本
【发布时间】:2016-09-30 21:43:02
【问题描述】:

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

为了尝试解决这个问题,我在我的应用程序类中实现了以下内容:

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()没有,那么在我从数据库中获取数据之前,所有的数据都丢失了。我想要的是,在更新应用程序时,我可以从数据库中获取版本,比较它是否是旧版本并将来自领域的数据存储在一个文件中,然后执行 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

【问题讨论】:

    标签: android realm data-migration


    【解决方案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,因此应用程序正常启动。

    【讨论】:

    • 应该RealmSchema 只是schema
    猜你喜欢
    • 2017-10-09
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    相关资源
    最近更新 更多