Realm Android Migration to change primary key data type not writing data

1.5k views Asked by At

I am using Realm android and wanted to change data type of existing primary key using Migration.

I used following code for Migration

schema.get("Test")
      .addField("id_new", String.class)
      .removeField("id")
      .addPrimaryKey("id_new")
      .renameField("id_new", "id");

Above code is migrating the schema without breaking, but if I try to write data in the new schema it is failing.

I don't want to persist any older data and thus not using transform method.

1

There are 1 answers

0
Sergei Bubenshchikov On

If you don't want to persist data, you can just call deleteRealmIfMigrationNeeded() method of builder:

RealmConfiguration config = new RealmConfiguration.Builder()
                                          .deleteRealmIfMigrationNeeded()
                                          .build();

but I think, it's posable ONLY for development cycle of application.

Released applications MUST have real migrations scripts. For yours question, I suggest to use:

schema.get("Test")
  .addField("id_new", String.class, FieldAttribute.PRIMARY_KEY)
  .transform(new RealmObjectSchema.Function() {
                    @Override
                    public void apply(DynamicRealmObject obj) {
                        // yuors transformation from id to id_new
                    }
                })
  .removeField("id")
  .renameField("id_new", "id");

See also:

Official docs

Migration sample class