2015-04-12 57 views
0

我試圖從我的應用程序購物車中執行項目刪除(我已使用本教程http://www.androiddom.com/2012/06/android-shopping-cart-tutorial-part-3.html)。執行從購物車中刪除項目

將商品添加到購物車時,我正在將商品詳細信息發送到購物車cartActivity,然後我在每個商品前面的購物車中都有編輯按鈕。一旦按下它就會進入編輯屏幕,相應地加載所有的數據。在editactivity我有刪除按鈕。我應該使用什麼作爲參考碼?如果是,我怎麼能得到這個代碼? 添加的每件商品都有一個產品編號,如下面的屏幕截圖所示。

enter image description here

如果您與傳遞項目的idCartActivityEditActivity面臨的問題我已經使用了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 


      } 
     }); 
+0

這裏居然是問題嗎? – skywall

+0

我不知道如何實現刪除選項,我試圖找到獲取一些id到我的編輯屏幕的方式,所以我可以確保我已經加載了相同的項目來從購物車活動編輯活動。 – modabeckham

+0

只需從cartMap中移除它(我想要使用Map來存儲購物車內容)並刷新您的用戶界面。 – skywall

回答

0

裏面,你可以使用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); 
} 
+0

我已經將getByProduct添加到ShoppingCartHelper.java中,接下來我應該怎麼做cartActivity? – modabeckham

+0

你可以直接調用'ShoppingCartHelper.removeProduct(product)' – skywall

+0

括號內的產品爲空,我怎樣才能將選擇的項目分配給產品 – modabeckham