Reputation: 358
I have an issue with getting Realm to migrate successfully and could do with a little help having been tinkering with it for a couple of weeks now..
I have a realm db working by which I mean saving data and and returning data.
Lets say I want to add a new field "username". I update my RealmObject code to utilise the new field. In my App.java I then use:
System.out.println("Configuring Realm...");
RealmConfiguration config1 = new RealmConfiguration.Builder(this)
.schemaVersion(1)
.migration(new Migration())
.build();
realm = Realm.getInstance(config1);
realm.close();
My Migration.java looks like:
public class Migration implements RealmMigration {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
RealmSchema schema = realm.getSchema();
RealmObjectSchema theSchema = schema.get("RealmStore");
System.out.println("Realm version is " + oldVersion);
if (oldVersion == 0) {
theSchema
.addField("username", String.class);
oldVersion++;
System.out.println("Realm migrated from 0 to 1");
}
}
}
I run the app and the following output is given:
I/System.out: Configuring Realm...
I/System.out: Realm version is 0
I/System.out: Realm migrated from 0 to 1
All good! Except..! When you re-run the app, you now get the following error:
E/AndroidRuntime: FATAL EXCEPTION: main
E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rh.realmy/com.rh.realmy.Main}: java.lang.IllegalArgumentException: Realm on disk is newer than the one specified: v1 vs. v0
Any ideas?
Upvotes: 2
Views: 1449
Reputation: 358
Kohi:
This is the code I used in the end (which works)...
In my App.java:
private Realm realm;
@Override
public void onCreate() {
super.onCreate();
// Setup Realm
RealmConfiguration config1 = new RealmConfiguration.Builder(this)
.schemaVersion(0)
.migration(new Migration())
.build();
realm = Realm.getInstance(config1); // Automatically run migration if needed
Realm.setDefaultConfiguration(config1);
realm.close();
}
}
In my class that uses realm:
private Realm realm;
@Override
protected void onCreate(Bundle savedInstanceState) {
// Open the default Realm for the UI thread.
realm = Realm.getDefaultInstance();
}
Then use realm as needed
Hope this helps
Upvotes: 2
Reputation: 20126
The problem is that in other parts of the code you are calling Realm.getInstance(context)
.
This is equivalent to doing the following:
RealmConfiguration config = new RealmConfiguration.Builder(context).schemaVersion(0).build();
Realm realm = Realm.getInstance(config);
Which will give you the schema mismatch error you are seeing.
You can read more about default configurations here: https://realm.io/docs/java/latest/#the-default-realm
Upvotes: 3