Realm sample code from the docs gives 'io.realm.exceptions.RealmException: Dog is not part of the schema for this Realm'

醉酒当歌 提交于 2020-01-06 04:32:06

问题


I'm trying to adapt for Kotlin a very simple piece of Java Realm code straight from the docs:

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

}

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

Then elsewhere I call:

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

I'd expect that Rex would be written to the DB (maybe I need to call executeTransaction first?) but instead I get the exception:

io.realm.exceptions.RealmException: Dog is not part of the schema for this Realm

How should I make Dog part of my scheme? Giving it a @PrimaryKey and id doesn't help.

UPDATE: I guess I need to add some schemas as I opened the default.realm and it's empty:

来源:https://stackoverflow.com/questions/51582830/realm-sample-code-from-the-docs-gives-io-realm-exceptions-realmexception-dog-i

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!