android - 在 Android 上的 Realm 中,我收到 "Field already exists"错误,但它是全新安装的吗?

标签 android migration realm

好的。所以我从 android 中完全删除了我的应用程序。然后在全新安装时出现错误

Field already exists in 'PortfolioCoin': color. 

为什么 realm 尝试在全新安装时迁移?

我在我的申请文件中得到了这个

    Realm.init(this);
    RealmConfiguration configuration = new RealmConfiguration.Builder()
            .name(Realm.DEFAULT_REALM_NAME)
            .schemaVersion(1)
            .migration(new Migration())
            //.deleteRealmIfMigrationNeeded()
            .build();
    Realm.setDefaultConfiguration(configuration);

    Realm.compactRealm(configuration);

这是我的迁移文件

public class Migration implements RealmMigration {

@Override
public void migrate(final DynamicRealm realm, long oldVersion, long newVersion) {
    // During a migration, a DynamicRealm is exposed. A DynamicRealm is an untyped variant of a normal Realm, but
    // with the same object creation and query capabilities.
    // A DynamicRealm uses Strings instead of Class references because the Classes might not even exist or have been
    // renamed.

    // Access the Realm schema in order to create, modify or delete classes and their fields.
    RealmSchema schema = realm.getSchema();


    if (oldVersion == 0) {

        RealmObjectSchema portfolioCoinSchema = schema.get("PortfolioCoin");
        portfolioCoinSchema
                .addField("color", int.class)
                .addField("totalValueBTC", double.class);

        oldVersion++;
    }

}

最佳答案

发生这种情况是因为您正在进行全新安装,其中已经包含字段“color”和“totalValueBTC”,然后您正尝试从默认值“oldVersion == 0”进行迁移.

所以您正在尝试添加已经存在的字段。

您应该检查不同的版本代码,或者在尝试通过迁移添加它之前,您应该使用“hasField(field)”方法检查它是否已经存在。

关于android - 在 Android 上的 Realm 中,我收到 "Field already exists"错误,但它是全新安装的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45179305/

相关文章:

android - 分析当前播放轨道的波形数据

java - 正确的字符集 |

css - Vaadin 14.6.1 - 错误 : Can't resolve 'lumo-css-framework/all-classes.css'

react-native - 升级后收到 "Unsupported Realm File Format"

android - 无法在 Android 模拟器上运行 AIR .apk 文件

java - 当 JSON 对象没有值的键时设置 null

Laravel 从现有模型生成迁移

ruby-on-rails-3 - RoR - 通过关联和迁移或 "by hand"(或脚手架)创建的外键?

java - 获取 io.realm.exceptions.RealmException : Could not find the generated ValidationList class when trying to get a Realm object

ios - 快速更新 Realm 数据库中的值