Android领域迁移:添加新领域列表列

时间:2015-05-28 19:56:55

标签: android migration realm realm-list realm-migration

我正在使用Realm v0.80.1,我正在尝试为我添加的新属性编写迁移代码。该房产是RealmList。我不知道如何正确添加新列或设置值。

我拥有的: customRealmTable.addColumn(," list");

如果正确添加了列,我将如何设置list属性的初始值?我想做点什么:

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

2 个答案:

答案 0 :(得分:12)

从Realm v1.0.0开始(也许之前),您只需调用RealmObjectSchema#addRealmListField(String, RealmObjectSchema)link to javadoc)即可实现此目的。例如,如果您尝试将permissions类型的RealmList<Permission>字段添加到User类,则可以写下:

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

Realm的迁移文档中还有一个示例here。为方便起见,这里是addRealmListField的完整javadoc:

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

答案 1 :(得分:5)

您可以在此处的示例中看到添加RealmList属性的示例:https://github.com/realm/realm-java/blob/master/examples/migrationExample/src/main/java/io/realm/examples/realmmigrationexample/model/Migration.java#L78-L78

相关代码是此部分:

   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++;
        }