每次创建新对象

时间:2015-06-14 01:21:46

标签: java android shopping-cart

我正在开发一个Android和新手的购物车应用程序。我现在面临一个问题。 我可以添加一个项目,然后将其添加到购物车中。我将项目数量添加到购物车后,可以编辑项目的数量或将其从列表视图中删除。

所以我想要的是禁用addToCart按钮(如果它已经存在于购物车中)以避免重复。但每次进入产品都被视为新条目。我想我没有正确引用它。任何帮助将不胜感激。

这是每次按下某个项目时调用的活动(例如:Dell内置笔记本电脑类别)

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.productdetails);
    LayoutInflater li;
    final List<Product> cart = ShoppingCartHelper.getCart();// get all //items from cart
    int productIndex = getIntent().getExtras().getInt(
            ShoppingCartHelper.PRODUCT_INDEX);// the item no in the list
    String PRODUCT_STRING = getIntent().getExtras().getString("PRODUCT");
    switch (PRODUCT_STRING) {
    case "Laptops":
        catalog = ShoppingCartHelper.getLaptopCatalog(getResources())
        break;
    case "Phones":
        catalog = ShoppingCartHelper
                .gePhonesCatalog(getResources());
        break;
    }
    final Product selectedProduct=(Product)this.catalog.get(productIndex);
// this declaration of product is taken as a new entry......................        
    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);

    final Button addToCartButton = (Button) findViewById(R.id.ButtonAddToCart);

    addToCartButton.setOnClickListener(new OnClickListener() {
        @Override

        public void onClick(View v) {
            cart.add(selectedProduct);
                selectedProduct.quantity ++;
            finish();
        }
    });     
    if(cart.contains(selectedProduct)) {
           addToCartButton.setEnabled(false);
           addToCartButton.setText("Item in Cart");
    }       
}

1 个答案:

答案 0 :(得分:0)

最快的解决方法是覆盖项目的equals()

否则,您的项目的每个实例都将被视为(并且 )与Java的视角不同。

以下是你如何做到的:

// Somewhere in your item's class..

@Override
public boolean equals(Object o) {
    if(!(o instanceof YourItem)
        return false;
    YourItem i = (YourItem) o;
    // This line below is based on my assumption, you should change to better suit your usecase.
    return this.getItemId() == i.getItemId();
}

当然,在上面的代码中,我假设你的项目有一个项目ID的字段和一个获取它的getter方法。请注意,它可能不适合您,您可能需要对其进行一些调整。

相关问题