Search code examples
realm

Migration is required due to Property id has been made required


it works fine if i change lateinit var id: String in the Payment.kt and CartPayment.kt to var id: String? = "", but the problem is i want the id to be required, how can i achieve that ?

The Error:

java.lang.RuntimeException: Unable to create application: io.realm.exceptions.RealmMigrationNeededException: Migration is required due to the following errors:
    - Property 'CartPayment.id' has been made required.
    - Property 'Payment.id' has been made required.

Model :

open class Payment() : RealmObject() {

    @PrimaryKey
    lateinit var id: String
    var typeValue: Int = 0
    var statusValue: Int = 0
    var value: Double = 0.0
    var referenceNumber: String? = null

Note: Payment and CartPayment models are identical except for the class name

Migration.kt

class Migration : RealmMigration {

    override fun migrate(realm: DynamicRealm, oldVersion: Long, newVersion: Long) {
        var oldVersion = oldVersion
        val schema = realm.schema

        if (oldVersion == 0L) {
            schema.create("Payment")
                .addField("id", String::class.java, FieldAttribute.PRIMARY_KEY)
                .addField("typeValue", Int::class.java)
                .addField("statusValue", Int::class.java)
                .addField("value", Double::class.java)
                .addField("referenceNumber", String::class.java)
            schema.get("Order")!!
                .addRealmListField("payments", schema.get("Payment")!!)
            oldVersion++
        }

        if (oldVersion == 1L) {
            schema.create("CartPayment")
                .addField("id", String::class.java, FieldAttribute.PRIMARY_KEY)
                .addField("typeValue", Int::class.java)
                .addField("statusValue", Int::class.java)
                .addField("value", Double::class.java)
                .addField("referenceNumber", String::class.java)
            schema.get("Order")!!
                .addField("cashPaymentAmount", Float::class.java)
                .addField("change", Float::class.java)
            oldVersion++
        }

    }
}

App.kt

class App: Application() {

    override fun onCreate() {
        super.onCreate()

        Realm.init(this)

        val realmConfig = RealmConfiguration.Builder()
            .schemaVersion(2)
            .migration(Migration())
            .build()
        Realm.getInstance(realmConfig)
        Realm.setDefaultConfiguration(realmConfig)

        Fresco.initialize(this)
    }
}


Solution

  • .addField("id", String::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED) did the trick.

    if you declare the variable to be lateinit, make sure to add FieldAttribute.REQUIRED.