io.realm.exceptions.RealmMigrationNeededException: Migration is required due to the following errors: - Class 'SaveMessage' has been added
Asked Answered
O

2

5

I am developing new app but I am getting following exception

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MessengerActivity}: io.realm.exceptions.RealmMigrationNeededException: Migration is required due to the following errors: - Class 'SaveMessage' has been added. at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3102) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3237) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:81) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1929) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:209) at android.app.ActivityThread.main(ActivityThread.java:7021) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:486) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:872) Caused by: io.realm.exceptions.RealmMigrationNeededException: Migration is required due to the following errors: - Class 'SaveMessage' has been added. at io.realm.internal.OsSharedRealm.nativeGetSharedRealm(Native Method) at io.realm.internal.OsSharedRealm.(OsSharedRealm.java:171) at io.realm.internal.OsSharedRealm.getInstance(OsSharedRealm.java:241) at io.realm.BaseRealm.(BaseRealm.java:136) at io.realm.BaseRealm.(BaseRealm.java:103) at io.realm.Realm.(Realm.java:163) at io.realm.Realm.createInstance(Realm.java:499) at io.realm.RealmCache.doCreateRealmOrGetFromCache(RealmCache.java:341) at io.realm.RealmCache.createRealmOrGetFromCache(RealmCache.java:284) at io.realm.Realm.getDefaultInstance(Realm.java:407) at com.example.myapplication.MessengerActivity.onCreate(MessengerActivity.java:92) at android.app.Activity.performCreate(Activity.java:7650) at android.app.Activity.performCreate(Activity.java:7639) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1295) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3077)

below is my code :

Realm.init(this);
        realm = Realm.getDefaultInstance();
        realm.beginTransaction();

        User userModel =  realm.createObject(User.class);


        Integer userId = Integer.valueOf("0");
        String userName = "Michael";

        userModel.setId(userId);
        userModel.setName(userName);
        //userModel.setIcon("icon");
        Integer userId1 = Integer.valueOf("1");
        String userName1 = "Lily";



        userModel.setId(userId1);
        userModel.setName(userName1);


        realm.commitTransaction();


        RealmResults<User> userModels = realm.where(User.class).findAll();
        for (User user : userModels) {
            Integer getId = Integer.valueOf(user.getId());
            String getName = user.getName();
            realm.commitTransaction();

        }

        SaveMessage saveModel = realm.createObject(SaveMessage.class);


       Integer saveId = Integer.valueOf("0");
       String savedName = "Michael";
        Integer saveIds = Integer.valueOf("1");
        String savedNames = "Lily";
        saveModel.setmId(saveId);
        saveModel.setmUsername(savedName);
        saveModel.setmContent("content");
        saveModel.ismRightMessage("isRightMessage");
        Date now = Calendar.getInstance().getTime();
        saveModel.setDate(now);
        realm.commitTransaction();



        RealmResults<SaveMessage> savesModels = realm.where(SaveMessage.class).findAll();
        for (SaveMessage saveMessage : savesModels) {
            Integer getId = saveMessage.getId();
            String getName = saveMessage.getUsername();
            String getContent = saveMessage.getContent();
            Date date = saveMessage.getDate();
            String rightMessage = String.valueOf(saveMessage.ismRightMessage());

            realm.commitTransaction();

        }

my SaveMessage model class :

@RealmClass
public class SaveMessage extends RealmObject {


    private int mId;
    private String mUsername;
    private String mContent;
    private Date mCreatedAt;
    private boolean mRightMessage;
    private String mPictureString;
    private String mType;

    public SaveMessage(int id, String username, String content, Date createdAt, boolean isRightMessage) {
        mId = id;
        mUsername = username;
        mContent = content;
        mCreatedAt = createdAt;
        mRightMessage = isRightMessage;
    }

    public SaveMessage() {

    }

    public int getId() {
        return mId;
    }

    public String getUsername() {
        return mUsername;
    }

    public String getContent() {
        return mContent;
    }

    public Date getDate() {
        return mCreatedAt;
    }

    public void setDate(Date createdAt) {


        mCreatedAt = createdAt;
    }




    public boolean ismRightMessage() {
        return mRightMessage;
    }

    public int getmId() {
        return mId;
    }

    public void setmId(int mId) {
        this.mId = mId;
    }

    public String getmUsername() {
        return mUsername;
    }

    public void setmUsername(String mUsername) {
        this.mUsername = mUsername;
    }

    public String getmContent() {
        return mContent;
    }

    public void setmContent(String mContent) {
        this.mContent = mContent;
    }


    public boolean ismRightMessage(String isRightMessage) {
        return mRightMessage;
    }

    public void setmRightMessage(boolean mRightMessage) {
        this.mRightMessage = mRightMessage;
    }

    public String getPictureString() {
        return mPictureString;
    }

    public void setPictureString(String pictureString) {
        mPictureString = pictureString;
    }

    public String getType() {
        return mType;
    }

    public void setType(String type) {
        mType = type;
    }



}
Oneeyed answered 6/5, 2019 at 8:26 Comment(0)
T
7

You added a new model in realm schema so you need to migrate your database. You can do this like this way:

  public class RealmUtility {
       private static final int SCHEMA_V_PREV = 1;// previous schema version
        private static final int SCHEMA_V_NOW = 2;// change schema version if any change happened in schema


        public static int getSchemaVNow() {
            return SCHEMA_V_NOW;
        }


        public static RealmConfiguration getDefaultConfig() {
            return new RealmConfiguration.Builder()
                    .schemaVersion(SCHEMA_V_NOW)
                    .deleteRealmIfMigrationNeeded()// if migration needed then this methoud will remove the existing database and will create new database
                    .build();
        }
}

if you don't want to delete your existing database and willing to add a new model in existing one then do like this way:

  public class RealmMigrations implements RealmMigration {

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

            if (oldVersion == 1) {
                final RealmObjectSchema saveMessage = 
                     schema.get("SaveMessage");
                      if(saveMessage==null){
                      saveMessage=realmSchema.create("SaveMessage");}
                      saveMessage.addField("mId", int.class);
                   // all field add here similarly
                         oldVersion++;
            }
        }
    }

    public static RealmConfiguration getDefaultConfig() {
            return new RealmConfiguration.Builder()
                    .schemaVersion(SCHEMA_V_NOW)
                     .migration(new RealmMigrations())               
                    .build();
        }

Then initialize realm like this way:

Realm realm = Realm.getInstance(RealmUtility.getDefaultConfig());
Toffee answered 6/5, 2019 at 8:51 Comment(5)
can you check your code again after adding your code get exceptionOneeyed
add here your exception @SwedenEdgarToffee
I am getting this exception java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MessengerActivity}: java.lang.IllegalStateException: Can't commit a non-existing write transaction in /Users/cm/Realm/realm-java-release/realm/realm-library/src/main/cpp/io_realm_internal_OsSharedRealm.cpp line 144Oneeyed
please check following exceptionOneeyed
remove realm.commitTransaction(); from inside for (SaveMessage saveMessage : savesModels) and for (User user : userModels). Also add realm.beginTransaction before SaveMessage saveModel = realm.createObject(SaveMessage.class); @SwedenEdgarToffee
A
2

During Realm migration I got the following error:-

java.lang.RuntimeException: Unable to create application com.merqueo.app.AppController: io.realm.exceptions.RealmMigrationNeededException: Migration is required due to the following errors:

Property 'User.departmentId' has been made optional.
Property 'User.taskId' has been made optional.

The reason for this was that model had a nullable field but migration was adding a not nullable field to DB.

Solution First:-

String::class.javaObjectType which will give you the wrapper class

Second:-

realm.schema.get("Class")?.apply {
    addField("departmentId", String::class.java).setNullable("departmentId", true)
    addField("taskId", String::class.java).setNullable("taskId", true)
}
Apo answered 2/12, 2021 at 6:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.