Actually Realm's migration example shows this scenario.
public class Migration implements RealmMigration {
@Override
public long execute(Realm realm, long version) {
// Step 0
if (version == 0) {
//Do the migration from 0 to 1
version++;
}
// Step 1
// Now the version is at least 1
if (version == 1) {
// Do the migration from 1 to 2
version++;
}
// Step 2
if (version == 2) {
// Do the migration from 2 to 3
version++;
}
// Now you get your final version 3
return version;
}
}
Simply just write the migration step by step, run them one by one until you get the latest schema version. For in your case, the user might have a Realm db version 0 here, and the step0 will run first. Then the version bump to 1 in the step 0 block, and the step 1 will run then.
------------ Update for user install version 3 directly case ------------
When create the realm instance, the code would be like:
RealmConfiguration config = new RealmConfiguration.Builder(this)
.migration(migration)
.schemaVersion(3)
.build();
Realm realm = Realm.getInstance(config);
Please notice that the schemaVersion(3)
here.
The RealmMigration.execute()
will only be executed if a migration is needed. This means if user install version 3 directly without having any previous version installed on the device, the RealmMigration.execute()
won't be called and the after the Realm file initialized, the schema version will be set to 3.