“需要领域迁移",android中的异常,同时从领域db检索值 [英] "realm migration needed", exception in android while retrieving values from realm db

查看:81
本文介绍了“需要领域迁移",android中的异常,同时从领域db检索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序中使用Realm作为后端.我创建了一个名为Setting的表.我按照Realm官方网站上给出的步骤在该表中添加了值. 但是,当我要从该表中检索值时,出现异常

I am using Realm as a back end in my application. I have created one table named Setting. I added values in that table, by following the steps given on Realm's official site. But when I am going to retrieve values from that table in, I getting exception

"io.realm.exceptions.RealmMigrationNeededException:必须提供RealmMigration":"realm = Realm.getInstance(getApplicationContext());".

"io.realm.exceptions.RealmMigrationNeededException: RealmMigration must be provided" on the line:" realm=Realm.getInstance(getApplicationContext());".

实际上,我是android和Realm的新手,所以很难理解问题所在.

Actually, I am new to android and Realm, so finding trouble to understand what is problem.

推荐答案

对于Realm的新版本,添加了Realm.init(上下文上下文)

for new versions of Realm, Realm.init(Context context) is added

Realm.init(context);    
RealmConfiguration config = new RealmConfiguration
                                     .Builder()
                                     .deleteRealmIfMigrationNeeded()
                                     .build();

注意:使用此配置选项,任何架构更改都会导致 数据丢失,特别是:

NOTE: With this config option, any schema change will result in loss of data, specifically:

  • 添加/删除字段
  • 添加了一个新的RealmObject类
  • 现有RealmObject被删除
  • @Required已添加/删除
  • @PrimaryKey已添加/删除
  • @Index已添加/删除
  • a field is added/removed
  • a new RealmObject class is added
  • an existing RealmObject is removed
  • @Required is added/removed
  • @PrimaryKey is added/removed
  • @Index is added/removed

因此,主要建议在应用处于开发阶段时使用.

So it's primarily recommended while the app is in the development stage.

或在官方文档之后添加迁移:

Or add a migration following the official docs:

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中的异常,同时从领域db检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆