首页 > 解决方案 > io.realm.exceptions.RealmMigrationNeededException:由于以下错误,需要迁移: - 添加了“SaveMessage”类

问题描述

我正在开发新应用程序,但出现以下异常

java.lang.RuntimeException:无法启动活动 ComponentInfo{com.example.myapplication/com.example.myapplication.MessengerActivity}:io.realm.exceptions.RealmMigrationNeededException:由于以下错误需要迁移:-“SaveMessage”类具有被添加。在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3102) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3237) 在 android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:81) 在 android。 app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 在 android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java: 1929) 在 android.os.Handler.dispatchMessage(Handler.java:106) 在 android.os.Looper.loop(Looper.java:209) 在 android.app.ActivityThread.main(ActivityThread.java:7021) 在 java。在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:486) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:872) 的 lang.reflect.Method.invoke(Native Method) ) 原因:io.realm.exceptions.RealmMigrationNeededException:由于以下错误需要迁移: - 添加了“SaveMessage”类。在 io.realm.internal.OsSharedRealm.nativeGetSharedRealm(Native Method) 在 io.realm.internal.OsSharedRealm.(OsSharedRealm.java:171) 在 io.realm.internal.OsSharedRealm.getInstance(OsSharedRealm.java:241) 在 io。领域。

下面是我的代码:

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();

        }

我的 SaveMessage 模型类:

@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;
    }



}

标签: androidrealmrealm-migration

解决方案


您在领域架构中添加了一个新模型,因此您需要迁移您的数据库。你可以这样做:

  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();
        }
}

如果您不想删除现有数据库并愿意在现有数据库中添加新模型,请这样做:

  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();
        }

然后像这样初始化领域:

Realm realm = Realm.getInstance(RealmUtility.getDefaultConfig());

推荐阅读