Juhani Juhani - 1 month ago 26
Android Question

Android Realm.io migration: Fallback to .deleteRealmIfMigrationNeeded()

When migrating an Android Realm.io instance to a newer schema I provide migration steps in my Migration implementation:

RealmConfiguration config = new RealmConfiguration
.Builder(this)
.schemaVersion(SCHEMA_VERSION)
.migration(new Migration())
.build();


What I want to do in the actual migration code I want to fallback to
deleteRealmIfMigrationNeeded
for older schema versions.

Is there any way to do that? I tried to do it with
deleteAll()
but that doesn't seem to work as some people updating from an older version of the app are getting Realm validation errors.

public class Migration implements RealmMigration {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {

if (oldVersion < 105) {
realm.deleteAll();
return;
}

//handle newer schema versions


}
}

Answer

You can try to open a Realm in dynamic mode and ask for it's version. DynamicRealms will not trigger migrations:

RealmConfiguration config = new RealmConfiguration
            .Builder(this)
            .schemaVersion(SCHEMA_VERSION)
            .migration(new Migration())
            .build();

// Use DynamicRealm to find version and delete it if it is too old
DynamicRealm dRealm = DynamicRealm.getInstance(config);
boolean delete = dRealm.getVersion() < 42;
dRealm.close();
if (delete) {
  Realm.deleteRealm(config);
}

Realm realm = Realm.getInstance(config);