2016-09-18 47 views
0

我有一个名为“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 
+0

好吧,试试显示'setSavedCombatants' – EpicPandaForce

回答

1

事实证明,你需要明确地保存对象里面的Re almList。

我需要我的SavedCombatant对象复制到里面的境界我对循环使用

mRealm.copyToRealm(combatants.get(i)); 
+0

是否有另一种方式来copyToRealm(名单)? –

+0

'for(E item:List items)copyToRealm(item);''也许? – TormundThunderfist

相关问题