eric
eric

Reputation: 215

How do I get the realm path in order to make a migration?

How would I get the realmPath if I'm trying to do a migration? I currently have something like this:

try {
    Realm realm = Realm.getInstance(this);
} catch (RealmMigrationNeededException e) {
    Realm.migrateRealmAtPath(???, new Migration());
}

Also, I have the following versions:

How do I make sure that users that upgrade from version 1 to version 3 and those that directly install version 3 will be updated to the latest schema version number (since they don't need to run the migration)?

Those going from v2 to v3 will get the version bump as a result of the migration running, but not sure how to set the Realm schema version.

Upvotes: 0

Views: 470

Answers (1)

Christian Melchior
Christian Melchior

Reputation: 20126

Christian from Realm here. The current Migration API is still very rough around the edges, so the only way to do that is by doing a migration that only increments the version number. So something like the below is probably the best way around it currently.

// Pseudo code
public static class RealmHelper {
    private static SharedPreferences prefs;
    public static Realm getInstance(Context context) {
        String realmPath = new File(context.getFilesDir(), "default.realm").getAbsolutePath();
        if (prefs.getBoolean("firstRun", true)) {
            Realm.migrateRealmAtPath(realmPath, new RealmMigration() {
                @Override
                public long migrate(Realm realm, long oldVersion) {
                    return 42; // new version of Realm
                }
            });
            prefs.edit().putBoolean("firstRun", false).commit();
        }

        try {
            return Realm.getInstance(context);
        } catch (RealmMigrationNeededException e) {
            Realm.migrateRealmAtPath(realmPath, new CustomMigration());
            return Realm.getInstance(context);
        }
    }
}

We are however hoping to make this a lot better very soon: https://github.com/realm/realm-java/pull/880

Upvotes: 1

Related Questions