Android Realm Migration: Adding new Realm list column

Steve Hernandez picture Steve Hernandez · May 28, 2015 · Viewed 10.9k times · Source

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

Vicky Chijwani picture Vicky Chijwani · Oct 5, 2016

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.
 */