Search code examples
androidrealmlogcat

Realm.getDefaultInstance(); error


The app firstly worked fine. But I decided to create package to make it more organized. Also, I created a new Class called Allegren; and generated getters and setters in it. You can see OcrApplication class below (it is where the error is).

OcrApplication class

package com.google.android.gms.samples.vision.ocrreader;


import com.google.android.gms.samples.vision.ocrreader.R;
import com.google.android.gms.samples.vision.ocrreader.realm.ingredients.Allergen;
import com.google.android.gms.samples.vision.ocrreader.realm.ingredients.Ingredient;

import io.realm.Realm;


public class OcrApplication extends android.app.Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this);
        Realm realm = Realm.getDefaultInstance();


        Allergen first_item = new Allergen();
        first_item.setName("FirstItem");
        first_item.setChecked(false);

        Ingredient aqua = new Ingredient();
        aqua.setName("Aqua");
        aqua.setDescription(getString(R.string.low)+ getString(R.string.aqua));

realm.beginTransaction();
realm.copyToRealm(first_item);
realm.copyToRealm(aqua);
realm.commitTransaction();
}
}

Logcat

Caused by: io.realm.exceptions.RealmMigrationNeededException: Migration is required due to the following errors:
    - Class 'Allergen' has been added.
        at io.realm.internal.OsSharedRealm.nativeGetSharedRealm(Native Method)
        at io.realm.internal.OsSharedRealm.<init>(OsSharedRealm.java:171)
        at io.realm.internal.OsSharedRealm.getInstance(OsSharedRealm.java:241)
        at io.realm.BaseRealm.<init>(BaseRealm.java:136)
        at io.realm.BaseRealm.<init>(BaseRealm.java:105)
        at io.realm.Realm.<init>(Realm.java:164)
        at io.realm.Realm.createInstance(Realm.java:435)
        at io.realm.RealmCache.doCreateRealmOrGetFromCache(RealmCache.java:342)
        at io.realm.RealmCache.createRealmOrGetFromCache(RealmCache.java:282)
        at io.realm.Realm.getDefaultInstance(Realm.java:343)
        at com.google.android.gms.samples.vision.ocrreader.OcrApplication.onCreate(OcrApplication.java:14)
        at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1014)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4855)

Solution

  • Each time you add a new table or edit an existing one in Realm, you need to create a new migration or else you get this error. Erasing the database and then creating it again from scratch as you did, solves the problem as well but it is bad practice and is mostly meant for when developing your app, not when it has been published.

    You can read more about realm migrations in the official Realm Docs.