Package io.realm

Interface RealmMigration


  • public interface RealmMigration
    The RealmMigration class is used to perform the migration of one Realm schema to another. The schema for a Realm is defined by all classes in a project that extend RealmObject or implement RealmModel, so any changes to these classes will require a migration.

    To support migrations from any previous schemaVersion to the newest, the following pattern is recommended when writing a migration:

     
     public class CustomMigration implements RealmMigration {
       \@Override
       public long migrate(DynamicRealm realm, long oldVersion, long newVersion) {
         RealmSchema schema = realm.getSchema();
    
         if (oldVersion == 0) {
           // Migrate from v0 to v1
           oldVersion++;
         }
    
         if (oldVersion == 1) {
           // Migrate from v1 to v2
           oldVersion++;
         }
    
         if (oldVersion < newVersion) {
             throw new IllegalStateException(String.format(Locale.US, "Migration missing from v%d to v%d", oldVersion, newVersion));
         }
       }
     }
     
     

    During development when RealmObject classes can change frequently, it is possible to use Realm.deleteRealm(RealmConfiguration). This will delete the database file and eliminate the need for any migrations.

    See Also:
    RealmConfiguration.Builder.schemaVersion(long), RealmConfiguration.Builder.migration(RealmMigration), RealmConfiguration.Builder.deleteRealmIfMigrationNeeded()
    • Method Detail

      • migrate

        void migrate​(DynamicRealm realm,
                     long oldVersion,
                     long newVersion)
        This method will be called if a migration is needed. The entire method is wrapped in a write transaction so it is possible to create, update or delete any existing objects without wrapping it in your own transaction.
        Parameters:
        realm - the Realm schema on which to perform the migration.
        oldVersion - the schema version of the Realm at the start of the migration.
        newVersion - the schema version of the Realm after executing the migration.