我在我的应用程序中使用 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 数据库中检索值时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33940233/