Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change datatype of Realm field - Java

Tags:

android

realm

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");
        }
like image 357
Gowtham Raj Avatar asked Jun 21 '16 13:06

Gowtham Raj


1 Answers

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");
like image 57
Christian Melchior Avatar answered Oct 19 '22 09:10

Christian Melchior