0

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:

enter image description here

Dave Chambers
  • 2,483
  • 2
  • 32
  • 55
  • This probably happened because you didn't add `apply plugin: 'kotlin-kapt'`. – EpicPandaForce Jul 29 '18 at 19:16
  • @EpicPandaForce I just saw your comment on https://stackoverflow.com/q/42947367/1390035 so tried to put apply plugin: 'realm-android' after the others but I get an error: Cannot change dependencies of configuration ':app:api' after it has been included in dependency resolution. – Dave Chambers Jul 29 '18 at 19:41

0 Answers0