我正尝试从the docs直接改编Kotlin一段非常简单的Java Realm
代码:
// Define your model class by extending RealmObject
class Dog : RealmObject() {
var name: String? = null
var age: Int = 0
}
class Person : RealmObject() {
@PrimaryKey
val id: Long = 0
val name: String? = null
val dogs: RealmList<Dog>? = null // Declare one-to-many relationships
}
在onCreate
中:
// Initialize Realm (just once per application)
Realm.init(this);
val config: RealmConfiguration = RealmConfiguration.Builder().name("default.realm").build()
Realm.setDefaultConfiguration(config)
realm = Realm.getDefaultInstance()
然后我在其他地方打电话给我
var dog = Dog()
dog.name = "Rex"
dog.age = 1
realm.beginTransaction()
var managedDog: Dog = realm.copyToRealm(dog)
val person = realm.createObject(Person::class.java)
person.dogs!!.add(managedDog)
realm.commitTransaction()
我希望Rex会被写入数据库(也许我需要先调用executeTransaction
?)但是我却得到了例外:
io.realm.exceptions.RealmException: Dog is not part of the schema for this Realm
我应该如何使Dog
成为计划的一部分?给它一个@PrimaryKey
和id
并没有帮助。
更新:我想我需要在打开default.realm
时添加一些架构,而且它是空的: