Search code examples
javaandroidjsoupbarcode-scanner

How to avoid addition of same item to the arraylist?


There is a POJO called Product in my project which contains fields like productName(String), costPrice(int), sellingPrice(int).

I'm scanning a barcode and putting the resultant number into the productName field of the Product.

Product product = new Product(UPC, 20,10);

Now, I'm putting this 'Product' POJO in an arraylist. I don't want products with same productName(i.e. same barcode number) to be added again and again.

if (arraylist.contains(product)) {
    Toast.makeText(getContext(), "Product already exists", Toast.LENGTH_SHORT).show();
} else {
    arraylist.add(product);
    adapter.notifyDataSetChanged();
}

But, since contains() method only checks if the same Product object exists in it and not the same UPC(barcode number), so it adds the Products with same UPC(barcode) number again and again.

Please tell me a way to check for the 'productName' field of the Product object so that duplicate productName (i.e. UPC/barcode number) can be avoided.


Solution

  • boolean isContains = false;
    String productName = product.getProductName();
    
    for (Product productItem : arraylist) {
        if (productItem.getProductName().equals(productName)) {
            isContains = true;
            break;
        }
    }
    
    if (isContains) {
        Toast.makeText(getContext(), "Product already exists", Toast.LENGTH_SHORT).show();
    } else {
        arraylist.add(product);
        adapter.notifyDataSetChanged();
    }
    

    Add productName in arraylist after full comparison