Sushant Sushant - 2 months ago 20
Android Question

Cannot remove item from Shopping Cart android studio

I referred [this][1] and [this][2] site and tried to modify it according to my own needs. Problem is I can't remove an item from the cart. I have tried everything including searching for solutions in stackoverflow and google but no luck.

Here is my CatalogActivity.java

package com.comlu.sush.shoppingcart;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import java.util.List;

public class CatalogActivity extends AppCompatActivity {

private List<Product> mProductList;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);

// Obtain a reference to the product catalog
mProductList = ShoppingCartHelper.getCatalog(getResources());

// Create the list
ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
listViewCatalog.setAdapter(new ProductAdapter(mProductList, getLayoutInflater(), false,false));

listViewCatalog.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX, position);
startActivity(productDetailsIntent);
}
});

Button viewShoppingCart = (Button) findViewById(R.id.ButtonViewCart);
viewShoppingCart.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
startActivity(viewShoppingCartIntent);
}
});

}
}


ShoppingCartHelper.java

package com.comlu.sush.shoppingcart;
import android.content.res.Resources;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

public class ShoppingCartHelper {
public static final String PRODUCT_INDEX = "PRODUCT_INDEX";
private static List<Product> catalog;
private static Map<Product, ShoppingCartEntry> cartMap = new HashMap<Product, ShoppingCartEntry>();

public static List<Product> getCatalog(Resources res){
if(catalog == null) {
catalog = new Vector<Product>();
catalog.add(new Product("Dead or Alive", res
.getDrawable(R.drawable.first),
"Dead or Alive by Tom Clancy with Grant Blackwood", 29.99));
catalog.add(new Product("Switch", res
.getDrawable(R.drawable.second),
"Switch by Chip Heath and Dan Heath", 24.99));
catalog.add(new Product("Watchmen", res
.getDrawable(R.drawable.third),
"Watchmen by Alan Moore and Dave Gibbons", 14.99));
}

return catalog;
}

public static void setQuantity(Product product, int quantity) {
// Get the current cart entry
ShoppingCartEntry curEntry = cartMap.get(product);

// If the quantity is zero or less, remove the products
if(quantity <= 0) {
if(curEntry != null)
removeProduct(product);
return;
}

// If a current cart entry doesn't exist, create one
if(curEntry == null) {
curEntry = new ShoppingCartEntry(product, quantity);
cartMap.put(product, curEntry);
return;
}

// Update the quantity
curEntry.setQuantity(quantity);
}

public static int getProductQuantity(Product product) {
// Get the current cart entry
ShoppingCartEntry curEntry = cartMap.get(product);

if(curEntry != null)
return curEntry.getQuantity();

return 0;
}

public static void removeProduct(Product product) {
cartMap.remove(product);
}

public static List<Product> getCartList() {
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
}

return cartList;
}
}


ShoppingCartActiity.java

package com.comlu.sush.shoppingcart;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import java.util.List;

public class ShoppingCartActivity extends AppCompatActivity {

private List<Product> mCartList;
private ProductAdapter mProductAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);

mCartList = ShoppingCartHelper.getCartList();

// Make sure to clear the selections
for(int i=0; i<mCartList.size(); i++) {
mCartList.get(i).selected = false;
}

// Create the list
final ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(), true,true);
listViewCatalog.setAdapter(mProductAdapter);

listViewCatalog.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
mProductAdapter.toggleSelection(position);

}
});

removeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

mProductAdapter.removeSelected();
}
});
}

@Override
protected void onResume() {
super.onResume();

// Refresh the data
if(mProductAdapter != null) {
mProductAdapter.notifyDataSetChanged();
}
}

}


ProductDetailsActivity.java

package com.comlu.sush.shoppingcart;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class ProductDetailsActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);

final int result=0;

List<Product> catalog = ShoppingCartHelper.getCatalog(getResources());

int productIndex = getIntent().getExtras().getInt(
ShoppingCartHelper.PRODUCT_INDEX);
final Product selectedProduct = catalog.get(productIndex);

// Set the proper image and text
ImageView productImageView = (ImageView) findViewById(R.id.ImageViewProduct);
productImageView.setImageDrawable(selectedProduct.productImage);
TextView productTitleTextView = (TextView) findViewById(R.id.TextViewProductTitle);
productTitleTextView.setText(selectedProduct.title);
TextView productDetailsTextView = (TextView) findViewById(R.id.TextViewProductDetails);
productDetailsTextView.setText(selectedProduct.description);

// Update the current quantity in the cart
TextView textViewCurrentQuantity = (TextView) findViewById(R.id.textViewCurrentlyInCart);
textViewCurrentQuantity.setText("Currently in Cart: "
+ ShoppingCartHelper.getProductQuantity(selectedProduct));


// Save a reference to the quantity edit text
final EditText editTextQuantity = (EditText) findViewById(R.id.editTextQuantity);

Button addToCartButton = (Button) findViewById(R.id.ButtonAddToCart);
addToCartButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

// Check to see that a valid quantity was entered
int quantity = 0;
try {
quantity = Integer.parseInt(editTextQuantity.getText()
.toString());

if (quantity < 0) {
Toast.makeText(getBaseContext(),
"Please enter a quantity of 0 or higher",
Toast.LENGTH_SHORT).show();
return;
}

} catch (Exception e) {
Toast.makeText(getBaseContext(),
"Please enter a numeric quantity",
Toast.LENGTH_SHORT).show();

return;
}

// If we make it here, a valid quantity was entered
ShoppingCartHelper.setQuantity(selectedProduct, quantity);

// Close the activity
finish();
}
});

}

}


ProductAdapter.java

package com.comlu.sush.shoppingcart;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class ProductAdapter extends BaseAdapter {

private List<Product> mProductList;
private LayoutInflater mInflater;
private boolean mShowQuantity;
private boolean mShowCheckbox;

public ProductAdapter(List<Product> list, LayoutInflater inflater, boolean showQuantity, boolean showCheckbox) {
mProductList = list;
mInflater = inflater;
mShowQuantity = showQuantity;
mShowCheckbox = showCheckbox;
}

@Override
public int getCount() {
return mProductList.size();
}

@Override
public Object getItem(int position) {
return mProductList.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewItem item;

if (convertView == null) {
convertView = mInflater.inflate(R.layout.item, null);
item = new ViewItem();

item.productImageView = (ImageView) convertView
.findViewById(R.id.ImageViewItem);

item.productTitle = (TextView) convertView
.findViewById(R.id.TextViewItem);

item.productQuantity = (TextView) convertView
.findViewById(R.id.textViewQuantity);

item.productCheckbox = (CheckBox) convertView.findViewById(R.id.CheckBoxSelected);

convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}

Product curProduct = mProductList.get(position);

item.productImageView.setImageDrawable(curProduct.productImage);
item.productTitle.setText(curProduct.title);

if(!mShowCheckbox) {
item.productCheckbox.setVisibility(View.GONE);
} else {
if(curProduct.selected == true)
item.productCheckbox.setChecked(true);
else
item.productCheckbox.setChecked(false);
}

// Show the quantity in the cart or not
if (mShowQuantity) {
item.productQuantity.setText("Quantity: "
+ ShoppingCartHelper.getProductQuantity(curProduct));
} else {
// Hid the view
item.productQuantity.setVisibility(View.GONE);
}

return convertView;
}
public void toggleSelection(int position) {
Product selectedProduct = (Product) getItem(position);
if(selectedProduct.selected) { // no need to check " == true"
selectedProduct.selected = false;
}
else {
selectedProduct.selected = true;
}
notifyDataSetInvalidated();
}
public void removeSelected() {
for(int i=mProductList.size()-1; i>=0; i--) {
if(mProductList.get(i).selected) {
mProductList.remove(i);
}
}
notifyDataSetChanged();
}
private class ViewItem {
ImageView productImageView;
TextView productTitle;
TextView productQuantity;
CheckBox productCheckbox;
}
}

Answer

Finally got it working because of @Sufian's small code snippet if(product.selected)

In the ShoppingCartHelper.java file

public static int getProductQuantity(Product product) {
        // Get the current cart entry
        ShoppingCartEntry curEntry = cartMap.get(product);

        if(product.selected == true)
        {
            removeProduct(product);
        }

        if(curEntry != null)
            return curEntry.getQuantity();

        return 0;
    }

This is the only change (and ofcourse there are a few other changes as suggested by @Sufian when he answered my question but that wasn't the complete answer so couldn't accept as it would have been misleading). Everything else and every other code is the same as posted in my question. For the full code please refer this website and apply the changes as I have mentioned. Hope this helps others who are trying this. And thanks to @Sufian again for this help.