我在我的应用程序中使用 Realm 作为后端。我创建了一个名为 Setting 的表。我按照 Realm 官方网站上给出的步骤在该表中添加了值。 但是当我要从该表中检索值时,出现异常
"io.realm.exceptions.RealmMigrationNeededException: RealmMigration must be provided" on the line:" realm=Realm.getInstance(getApplicationContext());".
实际上,我是android和Realm的新手,所以找麻烦了解问题所在。
最佳答案
EDIT: for new versions of Realm, Realm.init(Context context) is added
Realm.init(context);
RealmConfiguration config = new RealmConfiguration
.Builder()
.deleteRealmIfMigrationNeeded()
.build();
注意:使用此配置选项,任何架构更改都将导致数据丢失,具体而言:
- 添加/删除字段
- 添加了一个新的 RealmObject 类
- 删除现有的 RealmObject
@Required
添加/删除@PrimaryKey
添加/删除@Index
添加/删除
因此主要推荐在应用处于开发阶段时使用。
或者按照官方文档添加迁移:
https://realm.io/docs/java/latest/#migrations
例如,
public class Migration implements RealmMigration {
@Override
public void migrate(final DynamicRealm realm, long oldVersion, long newVersion) {
RealmSchema schema = realm.getSchema();
if (oldVersion == 0) {
RealmObjectSchema personSchema = schema.get("Person");
personSchema
.addField("fullName", String.class, FieldAttribute.REQUIRED);
oldVersion++;
...
// hash code, equals
和
Realm.init(context);
RealmConfiguration config = new RealmConfiguration.Builder()
.migration(new Migration())
// .deleteRealmIfMigrationNeeded()
.build();
关于android - "realm migration needed",从 Realm 数据库中检索值时 android 出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41949711/