Transform an object to a list[object] in Realm as migration(How can i replace a list[objects] with object field in Realm?)

Transform an object to a list[object] in Realm as migration ( How can i replace a list[objects] with object field in Realm? )

我想将现有的 token 作为第一项导入到 tokenList 中,例如,如果某人有 token="abc"migration 之后,我希望 he/she 有 tokenListtokenList[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;

在我的旧版本中 class :

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

我在 Realm GitHub 中创建了新的 issue 然后我找到了 [=25= 的正确方法]transform object to list[object] in Realm and insert existing object from previous version to new version of application.

在这个例子中我们想要transform Token object to tokenList[Token] in Bank model.

在迁移的最后一个版本中放这个:

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");
        }
}