android - 无法避免 io.realm.exceptions.RealmMigrationNeededException

标签 android realm

我想在我的模型中添加新字段

public class NoteModel extends RealmObject {
    @PrimaryKey
    private int id; //new field
    private String note;
    private String header;
    private Date date;
    /*
     * few getters and setters
     */

}

我不想做任何迁移

public class BaseApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this);
        //if I'm right it's delete all data from db and change it's schema (that's OK for me)
        RealmConfiguration config = new RealmConfiguration.Builder()
                .deleteRealmIfMigrationNeeded()
                .build()
    }
}

但我仍然遇到异常 io.realm.exceptions.RealmMigrationNeededException: Migration is required due to the following errors: - 添加了“NoteModel”类的主键。 - 添加了属性“NoteModel.id”。

它发生在 onCreate 方法 (MainActivity.java) 中。

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
realm = Realm.getDefaultInstance();      //error right here

我应该怎么做? 从这里获取信息:"realm migration needed", exception in android while retrieving values from realm db

最佳答案

创建上述配置后,您需要调用 Realm.setDefaultConfiguration(config)

public class BaseApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this);
        RealmConfiguration config = new RealmConfiguration.Builder()
                .deleteRealmIfMigrationNeeded()
                .build()
        Realm.setDefaultConfiguration(config); // <---
    }
}

关于android - 无法避免 io.realm.exceptions.RealmMigrationNeededException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47716907/

相关文章:

android - 从 Realm.io android 中删除单个对象(如果它仍然存在)

ios - 复合键问题 Realm Swift

php - 在 php 脚本中执行 curl 命令并从服务器获取响应并提取它

Android - 带有自定义 View 选项卡的 tablayout - 无法应用可绘制选择器

android - 为什么 TextView 中的文本在回收器 View 中被截断?

Android - 意外的顶级异常 :Execution failed for task ':app:dexDebug'

ios - 在一个项目中有两个 Realm 数据库并将其合并

java - 如何将 RealmResults<Model> 转换为 ArrayList<Model>?

android - 通过数据绑定(bind)将字符串传递给包含的布局不起作用

swift - 将 SwiftUI 与自定义发布者结合起来 - 使用 .assign 订阅者时出现意外行为