简体   繁体   中英

Realm clear DB when the class changes

Why is Realm completely cleared when changing the database class? That is, I had a class Weapon.class

public class Weapon extends RealmObject {

    @PrimaryKey
    private int ID;
    private String NameWeapon;

    //Constructor, getters, setters...

}

And everything is fine, the data is saved and read without problems, when adding new entries nothing flies. But, for example, I need to change the class

public class Weapon extends RealmObject {

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

    //Constructor, getters, setters...

}

I added a new variable to the class, and if I start the application, it will crash, because there will not be anything in the database, Realm will not let the old records be read. And if you rebuild the database (insert the records by default), then the data that was entered by the user will be lost.

The reason why my database was deleted:

MyApp.class

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

I completely forgot about this moment. It turns out I myself instructed everyone to delete ( .deleteRealmIfMigrationNeeded() ) when the database is migrating

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++;
    }
}

More Info: https://github.com/realm/realm-java/tree/master/examples/migrationExample/src/main/java/io/realm/examples/realmmigrationexample

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM