Pregunta

It's my first question here, I have been looking for a answer a few weeks. My work is an app project that represents a purchase cart, that scans a QR code of the product and adds it into a ListView. My problem is when I try to add a product that already exists in the list the app should increase this product quantity. It works perfectly until I add a third product, then the app thows a CurrentModificationException.

public void addProduto(Produto p) {
    //Check if the list is empty
    if (listItems.isEmpty()) {

        listItems.add(p);
    } else {
        for (Produto p2 : listItems) {

            //Verify if has a product in list with the same name
            if (p2.getName().equalsIgnoreCase(p.getName())) {

                //increase the product quantity
                p.setQuantity((int) (p2.getQuantity() + 1));

                //then replace the curent product by the new one
                listItems.set(listItems.indexOf(p2), p);
            } else {
                listItems.add(p);
            }
        }
    }
    adapter.notifyDataSetChanged();
}

I found some solutions for "CurrentModificationException", but they don't work in my code because I'm not trying to remove a row. I'm trying to update it, that's the point. In some examples that I found they use an Iterator to remove a row, but Iterator doesn't have a method to update.

¿Fue útil?

Solución

Instead of adding p to the list, can't you just update p2? That way you don't have to modify the list while iterating.
Also, your logic is a bit off, you need to have the if inside the for loop. Here is one way of doing it:

boolean foundIt = false;
for (Produto p2 : listItems) {
    //Verify if has a product in list with the same name
    if (p2.getName().equalsIgnoreCase(p.getName())) {
        //increase the product quantity
        p2.setQuantity((int) (p2.getQuantity() + 1));
        foundIt = true;
        break;
    }
}
if (!foundIt) {
    listItems.add(p);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top