我想在我的模型中添加新字段
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/