在我当前的应用程序中,我有一个带有“machineId”的HolderObject
(扩展)。在应用程序的新版本中,这将能够以 RealmList 的形式包含更多机器。请参阅以下课程:RealmObject
long
HolderObject
旧对象:
public class HolderObject extends RealmObject{
private long machineId;
//.. getters and setters
}
新对象:
public class HolderObject extends RealmObject{
private RealmList<RealmLong> machineIds;
//.. getters and setters
}
其中RealmLong
如下:
public class RealmLong extends RealmObject {
private long val;
//.. getters and setters
}
要将所有旧HolderObject
s 迁移到新对象,我使用自定义 RealmMigration。如下:
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();
}
});
}
}
问题:
- 在该行
obj.getList("machineIds").add(realmLong);
中,我收到此函数需要 aDynamicRealmObject
而不是 a的错误RealmLong
。我怎样才能RealmLong
在这个列表中添加一个? - (奖励问题)这是解决此迁移问题的正确和最佳方法吗?