In my current app, I have a HolderObject
(which extends RealmObject
) with a long
'machineId'. In a new version of the app, this HolderObject
will be able to contain more machines, in the form of a RealmList. See the classes below:
Old object:
public class HolderObject extends RealmObject{
private long machineId;
//.. getters and setters
}
New object:
public class HolderObject extends RealmObject{
private RealmList<RealmLong> machineIds;
//.. getters and setters
}
In which RealmLong
is as follows:
public class RealmLong extends RealmObject {
private long val;
//.. getters and setters
}
To migrate all old HolderObject
s to the new objects, I use my custom RealmMigration. This is as follows:
public class CustomRealmMigration implements RealmMigration {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
RealmSchema schema = realm.getSchema();
schema.get("HolderObject")
.addRealmListField("machineIds", schema.get("RealmLong"))
.transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
RealmLong realmLong = realm.createObject(RealmLong.class);
realmLong.setVal(obj.getLong("machineId"));
obj.getList("machineIds").add(realmLong);
realm.commitTransaction();
realm.close();
}
});
}
}
Question:
- In the line
obj.getList("machineIds").add(realmLong);
, I get the error that this function expects aDynamicRealmObject
, not aRealmLong
. How can I add aRealmLong
to this list? - (Bonus question) Is this the correct and best approach to this migration problem?