Ultimate Guide to Realm Database Migration in Android

If you are using Realm Database in your Android App, you must have faced the migration issue while submitting new versions. If we don’t migrate Realm database properly, it causes crashes when users update the App. This article is a guide to Realm database migration in Android.

Basic Realm Database Migration Steps

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

Realm.init(this);
// Realm Migration
RealmConfiguration config = new RealmConfiguration.Builder()
            .schemaVersion(3) // 1 // Must be bumped when the schema changes
            .migration(new RealmMigration() {  // Migration to run
                @Override
                public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
                    RealmSchema schema = realm.getSchema();

                    // Add your Migration Logic Here

                     if (oldVersion == 1) {
                       RealmObjectSchema newRealmModel = schema.create("NewRealmModel"); // if a new Realm class is added
                       newRealmModel.addField("user_id", int.class); // add all fields here
                   }

                   if (oldVersion == 2) {
                       // If adding new field in existing class
                       RealmObjectSchema newRealmModel = schema.get("NewRealmModel"); // if a new Realm class is added
                       newRealmModel.addField("user_name", String.class); // add all fields here
                   }
                       
                }
            }).build();

Realm.setDefaultConfiguration(config);

You just need to call this method once after initializing Realm. After that you can get Realm Object anywhere in your code, using Realm.getDefaultInstance(); method.

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 add or remove property in the existing Realm class or create a new Realm class, we 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(...) method in the above code. Actually we need to tell Realm about the new Realm classes we added or any new property is added or removed from an existing Realm class.

Troubleshooting

The above migration code will work perfectly if the user first migrates from version 1 to 2, then migrate from 2 to 3. But what if the user directly migrates from version 1 to 3? In that scenario above code will crash. Because 2nd if block will not execute in that scenario and “user_name” filed will not be added. For that, we can adjust our logic with the newVersion variable coming in the migrate(...) function as a parameter. Or the best way is to check in schema either the field is already present or not, and add only if it’s not present. as shown below.

if (!schema.contains("NewRealmModel")) {
          RealmObjectSchema newRealmModel = schema.create("NotificationUserRealmModel");
          newRealmModel.addField("user_id", int.class);
          newRealmModel.addField("user_name", String.class);
} else { // if NewRealmModel already exists
          RealmObjectSchema newRealmModel = schema.get("NewRealmModel"); // if a new Realm class is already added
          if (!newRealmModel.hasField("user_name")) {
               newRealmModel.addField("user_name", String.class);
          }
}

In this scenario, we even don’t need to check the old and new schema versions. We directly can check the fields, if those are not present we can add them.

That’s it. Feel free to add your suggestions in comments.

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

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

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: