从购物车中实施项目删除

时间:2015-04-12 07:09:17

标签: android shopping-cart

我尝试从我的应用购物车中实施项目删除(我已经使用了本教程http://www.androiddom.com/2012/06/android-shopping-cart-tutorial-part-3.html)。

将商品添加到购物车时,我正在做的是将商品详细信息发送到购物车cartActivity,然后我在每个商品前面的购物车中编辑按钮。按下它后,它进入编辑屏幕,相应地加载所有数据。在editactivity我有删除按钮。我应该使用什么作为参考代码?如果是,我该如何获得该代码? 添加的每个项目都有一个产品编号,如下面的屏幕截图所示。

enter image description here

我使用了ShoppingCartHelper.java

public class ShoppingCartHelper {

    private static Map<Product, ShoppingCartEntry> cartMap = new HashMap<Product, ShoppingCartEntry>();

    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;
    }

}

editactivity.java

deleteCartButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                ShoppingCartHelper.removeProduct(product); //how can I get the product here, it says to define it


            }
        });

1 个答案:

答案 0 :(得分:0)

如果您将项目idCartActivity传递到EditActivity时遇到问题,可以使用Intent个额外内容:

Intent intent = new Intent(this, EditActivity.class);
intent.putExtra("id", product.id); // id must be long
startActivity(intent);

EditActivity.java

Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    long id = getIntent().getLongExtra("id", 0);
    ...
}

如果您无法获取ShoppingCartEntry个实例,但是您拥有Product个实例,则可以将以下方法添加到ShoppingCartHelper.java

public ShoppingCartEntry getByProduct(Product product) {
    return cartMap.get(product);
}