Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 521
Steve Hernandez Avatar asked May 28 '15 19:05

Steve Hernandez


2 Answers

As of Realm v1.0.0 (and maybe before), you can simply call RealmObjectSchema#addRealmListField(String, RealmObjectSchema) (link to javadoc) to achieve this. For example, if you're trying to add a permissions field of type RealmList<Permission> to your User class, you'd write:

if (!schema.get("User").hasField("permissions")) {
    schema.get("User").addRealmListField("permissions", schema.get("Permission"));
}

There is also an example in Realm's migration docs here. And here is the full javadoc for addRealmListField, for convenience:

/**
 * Adds a new field that references a {@link RealmList}.
 *
 * @param fieldName  name of the field to add.
 * @param objectSchema schema for the Realm type being referenced.
 * @return the updated schema.
 * @throws IllegalArgumentException if the field name is illegal or a field with that name already exists.
 */
like image 95
Vicky Chijwani Avatar answered Nov 03 '22 02:11

Vicky Chijwani


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++;
        }
like image 7
Christian Melchior Avatar answered Nov 03 '22 00:11

Christian Melchior