I would like to change the data type of a Realm field from String
to int
and FYI the field is also a Primary Key
. I couldn't find a method in RealmMigration
to solve this issue.
PS : My app is already in production and all the values that are currently in that field are integers.
EDIT 1
My Model class
public class Team extends RealmObject {
@SerializedName("id")
@PrimaryKey
private int id;
@SerializedName("name")
private String name;
@SerializedName("description")
private String description;
}
my migration after trying Christian's answer
if (oldVersion == 6) {
RealmObjectSchema teamSchema = schema.get("Team");
teamSchema.addField("temp_id", int.class)
.transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
obj.setInt("temp_id", Integer.valueOf(obj.getString("id")));
}
})
.removeField("id")
.renameField("temp_id", "id")
.addPrimaryKey("id");
}
There isn't an one-liner method, but you can follow the same pattern as in our Migration example: https://github.com/realm/realm-java/blob/master/examples/migrationExample/src/main/java/io/realm/examples/realmmigrationexample/model/Migration.java#L132-L132
schema.get("MyClass")
.addField("new_key", int.class)
.transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
obj.setInt("new_key", Integer.valueOf(obj.getString("old_key")));
}
})
.removeField("old_key")
.addPrimaryKey("new_key")
.renameField("new_key", "old_key");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With