0

My application logs data about incoming phone calls and sms for particular dates and keeps them in a list. I want the application to check if there is already an entry for that date when a new phone call or sms comes in. If this is the case, I want the application to increment a value in the list.

However, when I try to do that I get this error: java.util.ConcurrentModificationException

How can I remedy this problem?

My codes looks like this

    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
}
Frederikkastrup
  • 243
  • 1
  • 3
  • 11
  • Typically a CME will happen if you change the value of something in the iterable you are working with while iterating over it. – Rogue Sep 29 '13 at 04:58
  • Your problem is no way related to Android. Therefore it is better that you *search* this site first using the `Java` tag. You would have found plenty advice. – A.H. Sep 29 '13 at 07:16

1 Answers1

1

A for loop, such as your for (Log log : logs), actually uses an Iterator underneath to iterate over the elements in the Collection (where logs is your Collection in this case).

A well-known fact about Iterator is that you must not attempt to modify the Collection while you're looping or iterating over it; to do otherwise will result in the ConcurrentModificationException.

There are already a large number of Q&As on SO regarding Iterator and CME, so rather than me duplicating advice, I advise looking at solutions offered here.

Community
  • 1
  • 1
Trevor
  • 10,903
  • 5
  • 61
  • 84