How to do a Realm migration in Android?

Migrations allow you to modify the schema of the application, which means that it lets you add, remove, rename tables/fields in the Realm schema. If you change a RealmModel class, then you must write the migration that will map the existing Realm file to reflect the new model classes.

RealmConfiguration config = new RealmConfiguration.Builder()
                                 .schemaVersion(1)
                                 .migration(new MyMigration()) 
                                 .build();
Realm.setDefaultConfiguration(config);

The default schema version is 0.


Migrations are fairly straightforward:

  • you must increment the schema version, so Realm knows you want to increment the schema's version to a specific number

  • you must supply a migration that will handle the change from one version to another

Migrations describe the operations to do when you need to go from one schema version to another:

public class MyMigration implements RealmMigration {

    @Override
    public void migrate(final DynamicRealm realm, long oldVersion, long newVersion) {
        RealmSchema schema = realm.getSchema();

        // Migrate from version 0 to version 1
        if (oldVersion == 0) {
            RealmObjectSchema userSchema = schema.get("User");

            userSchema.addField("testRealm", String.class);
            oldVersion++;
        }

        if (oldVersion == 1) { // ...
            // ...
        }
    }

    @Override
    public int hashCode() { return MyMigration.class.hashCode(); }

    @Override
    public boolean equals(Object object) { return object != null && object instanceof MyMigration; }
}

Tags:

Android

Realm