在Realm中将对象转换为list

在Realm中将对象转换为list

本文介绍了在Realm中将对象转换为list [object](如何在Realm中用对象字段替换list [object]?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将现有的token作为第一项导入到tokenList中,例如,如果某人有一个 token="abc"之后的token="abc",我希望他/她具有tokenList那个tokenList[0]=="abc"

I want to import existing token into tokenList as first item , for example if someone has a token="abc" after migration , i want he/she has tokenList that tokenList[0]=="abc"

这是我的迁移代码:

public class RealmMigration implements io.realm.RealmMigration {
.
.
.
    if (oldVersion == 3) {
        final RealmObjectSchema bankSchema = realmSchema.get("Bank");
        final RealmObjectSchema tokenSchema = realmSchema.get("Token");
        DynamicRealmObject bank = realm.createObject("Bank",1);
        Token token = bank.get("Token");
        bankSchema.addRealmListField("tokenList", tokenSchema);
        List<Token> tokenList = bank.get("tokenList");
        if (token != null) tokenList.add(token);
        bankSchema.removeField("Token");
    }
}

我将其替换为新版本:

@RealmField(name = "tokenList")
private RealmList<Token> mTokenList;

在我的课堂上,这是旧版本:

With this in old version in my class :

@RealmField(name = "Token")
private Token mToken;

推荐答案

我创建了新的 Realm GitHub 中发出noreferrer>问题 ,然后在 Realm 中找到了将转换 object转换为list[object]的正确方法insert现有对象.

I created new issue in Realm GitHub then i found right way for transform object to list[object] in Realm and insert existing object from previous version to new version of application.

在此示例中,我们希望在Bank模型中将transform Token 对象设置为tokenList[Token].

In this example we want to transform Token object to tokenList[Token] in Bank model.

在迁移的最新版本中输入以下内容:

In last version of migration put this :

public class RealmMigration implements io.realm.RealmMigration {

.

.

.

        if (oldVersion == 3) {
            //Create a schema for Bank
            final RealmObjectSchema bankSchema = realmSchema.get("Bank");
            //Create a schema for Token that has been in Bank model
            final RealmObjectSchema tokenSchema = realmSchema.get("Token");
            //We use bankSchema for add tokenList field and transform
            bankSchema
                .addRealmListField("tokenList", tokenSchema)
                .transform((obj) -> {//obj is bank model,we have a transform in bank model
                         DynamicRealmObject token = obj.get("Token");
                         List<DynamicRealmObject> tokenList = obj.get("tokenList");
                                //We add token from pre version to tokenList in new version
                                if (token != null) tokenList.add(token);
                            }
                    )
                    //Finally remove unwanted field
                    .removeField("Token");
        }
}

这篇关于在Realm中将对象转换为list [object](如何在Realm中用对象字段替换list [object]?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 14:07