copyToRealm 复制一个空列表而不是填充的列表

copyToRealm copies an empty list instead of a populated one

我有一个名为 "Encounter" 的 RealmObject,它包含一个名为 "SavedCombatant" 的其他 RealmObject 的 RealmList。在我的代码中,我用适当的 objects 填充了 RealmList,但是当我提交事务并稍后检索 Encounter-Object 时,RealmList 是空的。

我有以下代码

    public void saveEncounter(){

        //create a new key for the encounter
        int key = 0;
        if(mRealm.where(Encounter.class).count() != 0) {
            RealmResults<Encounter> encounters = mRealm.where(Encounter.class).findAll();
            Encounter encounter = encounters.last();
            key = encounter != null ? encounter.getKey() + 1 : 0;
        }

        // retrieve the data to populate the realmlist with
        // combatants has 1 element
        List<SavedCombatant> combatants = mAdapter.getCombatants();
        mRealm.beginTransaction();
        Encounter e = mRealm.createObject(Encounter.class);
        e.setKey(key);
        e.setTitle(txtTitle.getText().toString());
        RealmList<SavedCombatant> combatantRealmList = new RealmList<>();
        for (int i = 0; i < combatants.size(); i++) {
            combatantRealmList.add(combatants.get(i));    
        }
        //combatantRealmList also has 1 element. setCombatants is a
        //generated Setter with a couple bits of additional logic in it
        e.setCombatants(combatantRealmList);
        mRealm.copyToRealm(e);
        mRealm.commitTransaction();
}

这将是我的邂逅class

    public class Encounter extends RealmObject {

    private int key;
    private String title;
    private RealmList<SavedCombatant> combatants;

    @Ignore
    private String contents;

    public void setCombatants(RealmList<SavedCombatant> combatants) {
        //simple setter
        this.combatants = combatants;

        //generate summary of the elements in my realmlist. (probably inefficient as hell, but that's not part of the problem)
        HashMap<String, Integer> countMap = new HashMap<>();
        for (int i = 0; i < combatants.size(); ++i) {
            String name = combatants.get(i).getName();
            int countUp = 1;
            if (countMap.containsKey(name)) {
                countUp = countMap.get(name) + 1;
                countMap.remove(name);
            }
            countMap.put(name, countUp);
        }
        contents = "";
        Object[] keys = countMap.keySet().toArray();
        for (int i = 0; i < keys.length; ++i) {
            contents += countMap.get(keys[i]) + "x " + keys[i];
            if (i + 1 < keys.length)
                contents += "\r\n";
        }
    }

    // here be more code, just a bunch of getters/setters
}

用于 RealmList 的 class 具有以下 header(以验证我在这里也使用了 RealmObject)

public class SavedCombatant extends RealmObject

事实证明,您需要将对象显式保存在 RealmList 中。

我需要使用

将我的 SavedCombatant 对象复制到我的 for 循环内的领域
mRealm.copyToRealm(combatants.get(i));