Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

realm

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


    }
}
like image 356
Juhani Avatar asked Dec 09 '25 19:12

Juhani


1 Answers

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);
like image 194
Christian Melchior Avatar answered Dec 13 '25 05:12

Christian Melchior