我有一个名为“Encounter”的RealmObject,它包含一个名为“SavedCombatant”的其他RealmObject的RealmList。在我的代码中,我使用适当的对象填充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();
}
这将是我的遭遇类
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的类具有以下标题(以验证我在此处使用RealmObject)
public class SavedCombatant extends RealmObject
答案 0 :(得分:1)
事实证明,您需要在RealmList中明确保存对象。
我需要使用
将我的SavedCombatant对象复制到for循环中的realmmRealm.copyToRealm(combatants.get(i));