user5001783 user5001783 - 1 month ago 22
Android Question

Right way of doing Realm Migration Android

We use Realm for our app. Our app has been beta released. Now I want to add a field to one of our realm objects. So I got to write RealmMigration and I wrote one too. The Question here is how to apply this Realm migration to my app. I use Realm.getInstance() get the realm instance whenever I want to something. Remember, Realm.getInstance() is being used in the entire app everytime, I want to access Realm database.

So, I am bit Queried on how to apply this migration? Any leads can be helpful. Thanks.

My RealmMigration is as follows.

public class RealmMigrationClass implements RealmMigration {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
if(oldVersion == 0) {
RealmSchema sessionSchema = realm.getSchema();

if(oldVersion == 0) {
RealmObjectSchema sessionObjSchema = sessionSchema.get("Session");
sessionObjSchema.addField("isSessionRecordingUploading", boolean.class, FieldAttribute.REQUIRED)
.transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
obj.set("isSessionRecordingUploading", false);
}
});


sessionObjSchema.setNullable("isSessionRecordingUploading",false);
oldVersion++;
}

}
}

}

public class Session extends RealmObject {

@PrimaryKey
private String id;
@Required
private Date date;
private double latitude;
private double longitude;
private String location;
private String note;
private String appVersion;
private String appType;
private String deviceModel;
private HeartRecording heart;
private TemperatureRecording temperature;
private LungsRecording lungs;
@NotNull
private boolean isSessionRecordingUploading;
private boolean sessionInfoUploaded;
private boolean lungsRecordingUploaded;
private boolean heartRecordingUploaded;

}


Removed Getter and Setters from RealmObject to cut short the Question. The exception occurred when I try to reinstall the app without uninstalling the previous one. Please advice.

Answer

It is describe here: https://realm.io/docs/java/latest/#migrations

But in essence, you just bump the schema version and set the configuration like this:

RealmConfiguration config = new RealmConfiguration.Builder(context)
    .schemaVersion(2) // Must be bumped when the schema changes
    .migration(new MyMigration()) // Migration to run
    .build();

Realm.setDefaultConfiguration(config);

// This will automatically trigger the migration if needed
Realm realm = Realm.getDefaultInstance();
Comments