我有一個名爲「Encounter」的RealmObject,其中包含一個名爲「SavedCombatant」的其他RealmObjects的RealmList。在我的代碼中,我使用適當的對象填充RealmList,但是當我提交事務並稍後檢索Encounter-Object時,RealmList爲空。copyToRealm複製一個空列表而不是填充的一個
我有以下代碼
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
好吧,試試顯示'setSavedCombatants' – EpicPandaForce