2013-09-29 139 views
0

我的應用程序記錄有關特定日期的傳入電話和短信的數據,並將它們保存在列表中。我希望應用程序在新電話或短信進入時檢查是否有該日期的條目。如果是這種情況,我希望應用程序在列表中增加一個值。遍歷對象列表後發生java.util.ConcurrentModificationException

然而,當我嘗試這樣做,我得到這個錯誤:java.util.ConcurrentModificationException

我怎樣才能解決這個問題呢?

我的代碼看起來像這樣

public void addLog(String phonenumber, String type, long date, int incoming, int outgoing) 
{ 
    //Check if log exists or else create it. 
    Log newLog = new Log(phonenumber, type, date, incoming, outgoing); 

    //Iterates through logs 
    for (Log log : logs) 
    { 
     if (log.getPhonenumber() == phonenumber && log.getDate() == date && log.getType() == type) 
     { 
      updateLog(newLog, log.getId()); 
     } 
     else 
     { 
      android.util.Log.i("Datamodel", "Adding log"); 
      logs.add(newLog); 
      //add to database 
     } 
    } 
} 

public void updateLog(Log newLog, long id) 
{ 

    //check for outgoing or incoming 
    if (newLog.getIncoming() == 1) 
    { 
     for (Log log : logs) 
     { 
      if (log.getId() == id) 
      { 
       //Increments incoming 
       int incoming = log.getIncoming(); 
       android.util.Log.i("Datamodel", "Updating incoming"); 
       log.setIncoming(incoming++); 
      } 
      else 
      { 
       //Increments outgoing 
       int outgoing = log.getOutgoing(); 

       android.util.Log.i("Datamodel", "Updating outgoing"); 
       log.setOutgoing(outgoing++); 
      } 
     } 
    } 
    //Update the list 
    //Add to database 
} 
+0

通常情況下,如果您在迭代迭代的迭代器中更改某個值時,CME將發生。 – Rogue

+0

您的問題與Android無關。因此,最好先*使用Java標籤搜索本網站。你會發現很多建議。 –

回答

1

一個for循環,如您for (Log log : logs),實際上使用的Iterator下遍歷在Collection元素(其中logs是你Collection在這種情況下)。

關於Iterator的一個衆所周知的事實是,在循環或迭代它時,您不得試圖修改Collection;否則將導致ConcurrentModificationException

已經有大量的Q &就SO關於Iterator和CME,所以不是我重複建議,我建議尋找解決方案提供here