Search code examples
kotlinmigrationrealm

How to overcome RealmMigrationNeededException error on android app


When I click on launcher icon of my android app, its crashes immediately. I check logcat error, its shows Migration is required due to the following errors: - Property 'PrintJobData.jobPageCount' has been removed.I'm using Realm database and language is kotlin. How to overcome this issue.

private val realmConfig: RealmConfiguration = RealmConfiguration.Builder()

        .name("database.realm")

// .deleteRealmIfMigrationNeeded()

        .schemaVersion(1)

        .build()


private var realm: Realm = Realm.getInstance(realmConfig)

Solution

  • you can delete your realm if a migration is needed:

    .deleteRealmIfMigrationNeeded()
    

    or you can write a custom migration for your realm and each change you make to your database MUST be handled in migration. NOTE: remember after your changes to your database you have to update schemaVersion and also add your custom migration to RealmConfiguration.Builder() like bellow:

    val config = RealmConfiguration.Builder()
            .name("yourRealmName.realm")
            .schemaVersion(2)
            .migration(CustomMigration())
            .build()
    

    you can learn how to write migration from this and the original document