简体   繁体   中英

How to migration in realm for new table in android?

I add a new table to my realm database. For migration, I try at this way:

 realm.schema.create("AddTodoModel")
      .addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY)
      .addField("title", String::class.java , FieldAttribute.INDEXED)
      .addField("list", RealmList::class.java , FieldAttribute.INDEXED)
      .addField("color", Int::class.java , FieldAttribute.INDEXED)

And this is AddTodoModel class:

open class AddTodoModel(
    @PrimaryKey
    var id: Long,
    var title: String,
    var list: RealmList<TodoModel>,
    var color: Int
) : RealmObject() {
    constructor() : this(0, "", RealmList<TodoModel>(), R.color.black)
}

And when start the app, I get this error:

java.lang.IllegalArgumentException: Use addRealmObjectField() instead to add fields that link to other RealmObjects: list

I just get this error when the app updated. So, How to fix this error and migrate to a new version?

After trying some way, I found the solution. Maybe someone needs this: I create a list as TodoModel class in the database, But I miss to create a migration for that. And also I need to use FieldAttribute.REQUIRED instead of FieldAttribute.INDEXED . So this is the final migration code:

 realm.schema.create("AddTodoModel")
      .addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY)
      .addField("title", String::class.java, FieldAttribute.REQUIRED)
      .addRealmListField(
           "list",
           realm.schema.create("TodoModel")
           .addField("isDone", Boolean::class.java, FieldAttribute.REQUIRED)
      )
      .addField("color", Int::class.java, FieldAttribute.REQUIRED)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM