Reputation: 385
I'm new to Realm. I'm using realm as a local db, and if the app is updated i don't want to lose data. What i did earlier is
public static Realm getRealmInstanse(){
RealmConfiguration config = new RealmConfiguration
.Builder()
.deleteRealmIfMigrationNeeded()
.build();
try {
return Realm.getInstance(config);
} catch (RealmMigrationNeededException e){
try {
Realm.deleteRealm(config);
//Realm file has been deleted.
return Realm.getInstance(config);
} catch (Exception ex){
throw ex;
//No Realm file to remove.
}
}
}
Now i think i should do the following:
public static Realm getRealmInstanse(){
RealmConfiguration config = new RealmConfiguration
.Builder()
.migration(new RealmMigration() {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
}
})
.build();
return Realm.getInstance(config);
}
What should i do inside migrate() method in order to copy the data? And what about schema, should i uses schema version and for what purposes?
And what is the logic of changing the schema? For example, if for some reason i will change the structure of the db, can i just change the schema inside migrate() method?
I've found this example but i don't know actually if it is saving data or just changing the schema
if (oldVersion == 0) {
RealmObjectSchema personSchema = schema.get("Person");
// Combine 'firstName' and 'lastName' in a new field called 'fullName'
personSchema
.addField("fullName", String.class, FieldAttribute.REQUIRED)
.transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
obj.set("fullName", obj.getString("firstName") + " " + obj.getString("lastName"));
}
})
.removeField("firstName")
.removeField("lastName");
oldVersion++;
}
Upvotes: 3
Views: 2071
Reputation: 43314
What should i do inside migrate() method in order to copy the data?
Nothing, data is automatically kept between app updates (provided you have not changed the schema while also doing deleteRealmIfMigrationNeeded()
).
If you change the database schema and have set deleteRealmIfMigrationNeeded()
, the data will be deleted in order to migrate to the new schema automatically.
If you change the database schema and have not set deleteRealmIfMigrationNeeded()
, you must provide a RealmMigration, or the app will crash with a "migration needed" exception.
For example, if for some reason i will change the structure of the db, can i just change the schema inside migrate() method?
Yes. You can interact with the DynamicRealm that is passed to @Override public void migrate()
to specify the changes required to migrate to a new schema version.
You should give Realm's migration documentation a read.
Sidenote: building the RealmConfiguration as you are doing in your code should not be done every time you request an instance. Rather, do it once, preferably in your Application class. Also see configuring a realm.
Upvotes: 6