在Android中完成Realm迁移时,以前的领域数据会丢失

时间:2016-01-21 06:16:57

标签: android realm

以前我使用0.82.0领域版本,现在我使用0.87.0版本。根据项目要求,我试图在现有领域架构中添加两个新表。

为此,我在下面添加了代码..

public class UnitDetails extends RealmObject {

    private int unitUid;

    private double noOfrooms;

    private int unitArea;

    private int fId;

    private int fNum;

    private int maxAvailablity;

    // and setters and getter methods

}

public class Quote extends RealmObject {

    private String qName;
    private String qLocation;

    // and setters and getter methods

}

和迁移代码如下,使用appication上下文创建RealmConfiguration实例,并在需要Realm实例的地方调用getRealmInstance()方法。

public class RealmUtils  {

    private static RealmConfiguration config;

    public static void createRealmConfig(Context context) { 

        config = new RealmConfiguration.Builder(context)
                .name("default.realm1")
                .schemaVersion(1)
                .migration(new CustomMigration())
                .build();
    }

    public static Realm getRealmInstance() { 

        return Realm.getInstance(config);
    }
}

public class CustomMigration implements RealmMigration {

    @Override
    public void migrate(final DynamicRealm realm, long oldVersion, long newVersion) {
        RealmSchema schema = realm.getSchema();
        if (oldVersion == 0) {
            RealmObjectSchema quoteSchema = schema.create("Quote")
                    .addField("qName", String.class)
                    .addField("qLocation", String.class);

            RealmObjectSchema unitDetailsSchema = schema.create("UnitDetails")
                    .addField("unitUid", int.class)
                    .addField("noOfrooms", double.class)
                    .addField("unitArea", int.class)
                    .addField("fId", int.class)
                    .addField("fNum", int.class)
                    .addField("maxAvailablity", int.class);
            oldVersion++;
        }
    }
}

当我通过安装新的apk更新我的应用程序时,我没有收到RealmMigrationNeededException,但之前的数据已丢失。

这里出了什么问题以及如何防止数据丢失?我是否需要对现有表格执行任何操作?我正在使用新领域版本时应该注意什么?

1 个答案:

答案 0 :(得分:3)

您也不应该更新名称,只更新版本号。以下配置应该有效:

public class RealmUtils  {

    private static RealmConfiguration config;

    public static void createRealmConfig(Context context) { 

        config = new RealmConfiguration.Builder(context)                                           
                .schemaVersion(1)
                .migration(new CustomMigration())
                .build();
    }

    public static Realm getRealmInstance() { 

        return Realm.getInstance(config);
    }
}