“realm migration needed”, exception in android while retrieving values from realm db

EDIT: for new versions of Realm, Realm.init(Context context) is added

Realm.init(context);    
RealmConfiguration config = new RealmConfiguration
                                     .Builder()
                                     .deleteRealmIfMigrationNeeded()
                                     .build();

NOTE: With this config option, any schema change will result in loss of data, specifically:

  • a field is added/removed
  • a new RealmObject class is added
  • an existing RealmObject is removed
  • @Required is added/removed
  • @PrimaryKey is added/removed
  • @Index is added/removed

So it’s primarily recommended while the app is in the development stage.


Or add a migration following the official docs:

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

For example,

public class Migration implements RealmMigration {
    @Override
    public void migrate(final DynamicRealm realm, long oldVersion, long newVersion) {
        RealmSchema schema = realm.getSchema();

        if (oldVersion == 0) {
            RealmObjectSchema personSchema = schema.get("Person");
            personSchema
                .addField("fullName", String.class, FieldAttribute.REQUIRED);
            oldVersion++;
            ... 

  // hash code, equals 

And

Realm.init(context);    
RealmConfiguration config = new RealmConfiguration.Builder() 
                                 .migration(new Migration()) 
                           //      .deleteRealmIfMigrationNeeded()
                                 .build();

Leave a Comment