I have a User object right now that has a bunch of values in it, saved as doubles
. The format of our api json is now changing to include two values for each field. So I have created a Value
object (which extends RealmObject
) and it contains the two values.
So now in my user object I want to do the following
//Current way
private Double balance;
//Want to migrate to this
private Value balance;
The Value
object looks like this:
private class Value extends RealmObject {
private Integer value;
private String formattedValue;
//getters/setters
}
My question is, how can I express this change in a RealmMigration
?
This is what I have so far based on this: (Change datatype of Realm field - Java)
schema.get("User")
.addField("balance_tmp", Value.class)
.transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
//what goes here? how can I access the Value.class and call setValue()?
}
})
.removeField("balance")
.renameField("balance_tmp", "balance");
Is this even possible? Or should I be resigned to fact that any data assigned to the fields I change will be lost?
Something like this should work:
RealmObjectSchema valueSchema = schema.create("Value")
.addField("value", Integer.class)
.addField("formattedValue", String.class);
schema.get("User")
.addRealmObjectField("balance_tmp", valueSchema)
.transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
int balance = obj.getInt("balance");
DynamicRealmObject valueObj = obj.getObject("balance_tmp");
valueObj.setInt("value", balance);
valueObj.setString("formattedValue", format(balance));
}
})
.removeField("balance")
.renameField("balance_tmp", "balance");