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: