Reputation: 540
I am having a problem incrementing my integer variable after a certain condition is met in Android Programming. Why is it not incrementing?
The code below are implemented on an ImageButton which lies a class (Activity) called Product.
int count = 1;
List<Item> prod = ShoppingCart.getInstance().getProducts();
// if arraylist is null --> add a product
if(prod != null && prod.isEmpty()){
ShoppingCart.getInstance().addItem(new Item(
namePureString,
manufacturePureString,
pricePureString,
"",
count
));
Toast.makeText(getApplicationContext(), namePureString + " Added To Cart", Toast.LENGTH_SHORT).show();
}else {
for (Item products : ShoppingCart.getInstance().myProducts) {
// here i am checking if the product exists, if it does --> count has to increment
if (products.getManufacture().equals(manufacturePureString)) {
count += count;
Toast.makeText(getApplicationContext(), "You Added This Product\nQuantity Will Increase",
Toast.LENGTH_SHORT).show();
ShoppingCart.getInstance().setItemExists(new Item(
namePureString,
manufacturePureString,
pricePureString,
"",
count
));
} else {
ShoppingCart.getInstance().addItem(new Item(
namePureString,
manufacturePureString,
pricePureString,
"",
count
));
}
}
This is my Singleton class, in which I call its methods:
public class ShoppingCart {
private static final String TAG = "Products: ";
private static ShoppingCart ourInstance = null;
public ArrayList<Item> myProducts = new ArrayList<>();
private ShoppingCart() {
}
public static ShoppingCart getInstance() {
// if object instance does not exist create a new one and use that one only
if ( ourInstance == null){
ourInstance = new ShoppingCart();
}
return ourInstance;
}
public void addItem(Item item){
ourInstance.myProducts.add(item);
}
public void setItemExists(Item item) {
int itemIndex = ourInstance.myProducts.indexOf(item);
if (itemIndex != -1) {
ourInstance.myProducts.set(itemIndex, item);
}
}
public List<Item> getProducts(){
return this.myProducts;
}
}
Upvotes: 3
Views: 5537
Reputation: 133
Try
int count = 0;
count = count + 1;
Log.d("Answer: ",count);
Upvotes: 2
Reputation: 46
count++ is the same as count = count + 1 and not count += count in your Code. Count += count adds the amount of count on top of the value of count.
So to increment add this:
count = count + 1;
//or
count++;
Upvotes: 3