当班级改变时,领域清除DB

时间:2017-04-19 14:16:52

标签: android database realm

更改数据库类时为什么Realm完全清除?也就是说,我上过课 的 Weapon.class

public class Weapon extends RealmObject {

    @PrimaryKey
    private int ID;
    private String NameWeapon;

    //Constructor, getters, setters...

}

一切都很好,数据保存和读取没有问题,添加新条目时没有任何问题。但是,例如,我需要更改类

public class Weapon extends RealmObject {

    @PrimaryKey
    private int ID;
    private String NameWeapon;
    private float Cost = 0f;

    //Constructor, getters, setters...

}

我在类中添加了一个新变量,如果我启动应用程序,它将崩溃,因为数据库中没有任何内容,Realm不会让旧记录被读取。如果重建数据库(默认情况下插入记录),则用户输入的数据将丢失。

1 个答案:

答案 0 :(得分:3)

我的数据库被删除的原因:

<强> MyApp.class的

mRealmConfiguration = new RealmConfiguration.Builder()
            .name(Constants.DATABASE_NAME_REALM)
            .schemaVersion(0)
            .deleteRealmIfMigrationNeeded()
            .build();

我完全忘记了这一刻。事实证明,我自己指示每个人在数据库迁移时删除(.deleteRealmIfMigrationNeeded()

mRealmConfiguration = new RealmConfiguration.Builder()
            .name(Constants.DATABASE_NAME_REALM)
            .schemaVersion(0)
            .migration(new Migration())
            .build();

<强> Migration.class

public class Migration implements RealmMigration {

    @Override
    public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {

    RealmSchema mSchema = realm.getSchema();

    /****************************************************************
     * Version 0
     *
        class Weapon
           @PrimaryKey
           private int ID;
           private String NameWeapon;

     *
     * Version 1
     *
         class Weapon
            @PrimaryKey
            private int ID;
            private String NameWeapon;
            private float Cost = 0f;
     ****************************************************************/

    if (oldVersion == 0) {
        RealmObjectSchema mPrimaryCaseSchema = mSchema.get("Weapon");

        mPrimaryCaseSchema
                .addField("Cost");
        oldVersion++;
    }
}

更多信息:https://github.com/realm/realm-java/tree/master/examples/migrationExample/src/main/java/io/realm/examples/realmmigrationexample

https://realm.io/docs/java/latest/#migrations