2014-04-01 38 views
0

這是我的第一個問題,幾周後我一直在尋找答案。我的工作是一個代表購物車的應用程序項目,它掃描產品的QR碼並將其添加到ListView中。我的問題是,當我嘗試添加列表中已存在的產品時,應用程序應增加此產品數量。直到我添加第三個產品,它才能正常工作,然後該應用程序拋出CurrentModificationException。當我嘗試更新一行時,Android ListView拋出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(); 
} 

我發現「CurrentModificationException」一些解決方案,但因爲我不是要刪除行不,我的代碼工作。我試圖更新它,這是重點。在一些例子中,我發現他們使用迭代器來刪除一行,但迭代器沒有更新的方法。

回答

0

而不是將p添加到列表中,你不能只是更新p2?這樣,您不必在迭代時修改列表。
另外,您的邏輯有點偏離,您需要在for循環內部有if。這裏有一種方法:

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); 
} 
+0

非常感謝很多人,它完美的工作!我是java開發的初學者,我非常感謝你的幫助。 – fdsilva

相關問題