Realm Database Migration in Android Using Kotlin

In this article, we will learn Realm Database Migration in Android using Kotlin. You must have faced the migration issue while submitting new versions. If we don’t migrate the Realm database properly, it causes crashes when users update the App.

Realm Database Migration Steps

Add the following migration code in your Application class after Realm.init(this); method call.

 Realm.init(this)
// Realm Migration
        val config = RealmConfiguration.Builder()
                .schemaVersion(3) // 1 // Must be bumped when the schema changes
                .migration { realm, oldVersion, newVersion ->

                    // Migration to run
                    val schema = realm.schema

                    // Add your Migration Logic Here
                    if (oldVersion == 1L) {
                        val newRealmModel = schema.create("NewRealmModel") // if a new Realm class is added
                        newRealmModel.addField("user_id", Int::class.javaPrimitiveType) // add all fields here
                    }
                    if (oldVersion == 2L) {
                        // If adding new field in existing class
                        val newRealmModel = schema["NewRealmModel"] // if a new Realm class is added
                        newRealmModel!!.addField("user_name", String::class.java) // add all fields here
                    }
                }.build()

        Realm.setDefaultConfiguration(config)

After Realm initialization you just need to call this method once. By using Realm.getDefaultInstance(); the method you can get Realm Object anywhere in your code.

Your Migration Logic

In the above code, you need to increase the schema version by value 1, every time when you make any change in Realm classes. Whenever we create a new Realm class or we add or remove property in the existing Realm class, we must have to need to increase the schema version and write migration logic. The default value of the schema version is 1.

Migration Logic should be written in migrate(...) the method in the above code. Actually, we need to tell Realm about the new Realm classes we added or any new property that is added or removed from an existing Realm class.
That’s it. Feel free to add your suggestions in the comments.

You can also find other useful helping articles, code snippets, and tutorials in our Tutorials Library.

Realm Database Migration in Java

Ultimate Guide to Realm Database Migration in Android

Please share this post:
Posts created 35

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: