io.realm.exceptions.RealmMigrationNeededException:由于以下错误,需要迁移:-已添加类'SaveMessage'

时间:2019-05-06 08:26:08

标签: android realm realm-migration

我正在开发新的应用程序,但是我却遇到了异常

  

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.lang.reflect.Method.invoke(本机方法)           在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:486)           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:872)        引起原因:io.realm.exceptions.RealmMigrationNeededException:由于以下错误,需要进行迁移:       -添加了“ SaveMessage”类。           在io.realm.internal.OsSharedRealm.nativeGetSharedRealm(本机方法)           在io.realm.internal.OsSharedRealm。(OsSharedRealm.java:171)           在io.realm.internal.OsSharedRealm.getInstance(OsSharedRealm.java:241)           在io.realm.BaseRealm(BaseRealm.java:136)           在io.realm.BaseRealm处(BaseRealm.java:103)           在io.realm.Realm(Realm.java:163)           在io.realm.Realm.createInstance(Realm.java:499)           在io.realm.RealmCache.doCreateRealmOrGetFromCache(RealmCache.java:341)           在io.realm.RealmCache.createRealmOrGetFromCache(RealmCache.java:284)           在io.realm.Realm.getDefaultInstance(Realm.java:407)           在com.example.myapplication.MessengerActivity.onCreate(MessengerActivity.java:92)           在android.app.Activity.performCreate(Activity.java:7650)           在android.app.Activity.performCreate(Activity.java:7639)           在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1295)           在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3077)

下面是我的代码:

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



}

1 个答案:

答案 0 :(得分:1)

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

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