Change datatype of Realm field - Java

天涯浪子 提交于 2019-12-23 08:52:20

问题


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");
        }

回答1:


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");


来源:https://stackoverflow.com/questions/37946076/change-datatype-of-realm-field-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!