Steve Hernandez Steve Hernandez - 2 months ago 44
Android Question

Android Realm Migration: Adding new Realm list column

Im using Realm v0.80.1 and I am trying to write migration code for a new property I added. The property is a RealmList. Im not sure how to properly add the new column or set a a value.

What I have:
customRealmTable.addColumn(, "list");

Once the column is properly added how would I go about setting an initial value for the list property? I would like to do something like:

customRealmTable.setRealmList(newColumnIndex, rowIndex, new RealmList<>());

Answer

You can see an example of adding a RealmList attribute in the examples here: https://github.com/realm/realm-java/blob/master/examples/migrationExample/src/main/java/io/realm/examples/realmmigrationexample/model/Migration.java#L78-L78

The relevant code is this section:

   if (version == 1) {
            Table personTable = realm.getTable(Person.class);
            Table petTable = realm.getTable(Pet.class);
            petTable.addColumn(ColumnType.STRING, "name");
            petTable.addColumn(ColumnType.STRING, "type");
            long petsIndex = personTable.addColumnLink(ColumnType.LINK_LIST, "pets", petTable);
            long fullNameIndex = getIndexForProperty(personTable, "fullName");

            for (int i = 0; i < personTable.size(); i++) {
                if (personTable.getString(fullNameIndex, i).equals("JP McDonald")) {
                    personTable.getRow(i).getLinkList(petsIndex).add(petTable.add("Jimbo", "dog"));
                }
            }
            version++;
        }