Home » Android » android – RealmMigrationNeededException when changing Realm model

android – RealmMigrationNeededException when changing Realm model

Posted by: admin June 15, 2020 Leave a comment

Questions:

Whenever I change the model like adding more fields, the app crash with io.realm.exceptions.RealmMigrationNeededException error. This can only be resolved when I uninstalled and reinstalled the app.

Any suggestion to do migration? I am using only the default instance.

How to&Answers:

You should be able to find the information you need here:

https://realm.io/docs/java/latest/#migrations

Just changing your code to the new definition will work fine, if you
have no data stored on disk under the old database schema. But if you
do, there will be a mismatch between what Realm sees defined in code &
the data Realm sees on disk, so an exception will be thrown.

Answer:

If you don’t have any problem in loosing your old data then you can delete Realm Configuration and create new one.

Realm realm = null;

                    try {
                       realm = Realm.getInstance(MainActivity.this);
                    } catch (RealmMigrationNeededException r) {
                        Realm.deleteRealmFile(MainActivity.this);
                        realm = Realm.getInstance(MainActivity.this);
                    }

OR

RealmConfiguration config2 = new RealmConfiguration.Builder(this)
                .name("default2") 
                .schemaVersion(3) 
                .deleteRealmIfMigrationNeeded() 
                .build(); 


        realm = Realm.getInstance(config2);

you have to do Migration if you don’t want to loose your data please see this example here.

Answer:

Realm migrations in 0.84.2 are changed quite a bit, the key points on making a realm (0.84.2) migration work for me were understanding that:

  • The schemaVersion is always 0 when your app has a realm db without
    specifying the schemaVersion. Which is true in most cases since you
    probably start using the schemaVersion in the configuration once you
    need migrations & are already running a live release of your app.

  • The schemaVersion is automatically stored and when a fresh install of your app occurs and you are already on schemaVersion 3, realm
    automatically checks if there are exceptions, if not it sets the
    schemaVersion to 3 so your migrations aren’t run when not needed.
    This also meens you don’t have to store anything anymore in
    SharedPreferences.

  • In the migration you have to set all values of new columns when the type is not nullable, …

  • Empty Strings can be inserted but only when setting convertColumnToNullable on the column