2013-09-29 92 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