我想在模型中添加新字段
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异常:由于以下错误,需要进行迁移:
-添加了类'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/