当用户多次在购物车中添加相同商品时,应该只添加该商品一次,并增加该商品的数量,但在我的情况下,每次都会添加整个商品。
下面是购物车活动:
public class CartActivity extends AppCompatActivity implements CartAdapter.OnCartDataChangeListener {
DatabaseHandler helper;
public static List<ProductModel> dbList;
RecyclerView mRecyclerView;
Toolbar toolbar;
Button btnCheckout, btnContinueShopping;
public TextView tvTotalNoOfItems, tvTotalPrice;
String productVaiantId;
String selectedProductId;
private RecyclerView.Adapter mAdapter;
private LinearLayoutManager mLayoutManager;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
productVaiantId = getIntent().getStringExtra("variant_id");
selectedProductId = getIntent().getStringExtra("product_id");
Bundle extras = getIntent().getExtras();
if (extras != null) {
productVaiantId = extras.getString("variant_id");
selectedProductId = extras.getString("product_id");
}
toolbar = (Toolbar) findViewById(R.id.customToolBar);
setSupportActionBar(toolbar);
setTitle("Check-out");
toolbar.setTitleTextColor(Color.BLACK);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
helper = new DatabaseHandler(this);
dbList = new ArrayList<ProductModel>();
dbList = helper.getDataFromDB();
mRecyclerView = (RecyclerView) findViewById(R.id.rv_cart_item_list);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mLayoutManager = new LinearLayoutManager(this) {
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
LinearSmoothScroller smoothScroller = new LinearSmoothScroller(CartActivity.this) {
private static final float SPEED = 300f;// Change this value (default=25f)
@Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return SPEED / displayMetrics.densityDpi;
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
};
mAdapter = new CartAdapter(this, dbList, this);
tvTotalNoOfItems = (TextView) findViewById(R.id.tvTotalCartItems);
tvTotalPrice = (TextView) findViewById(R.id.tvTotalCartItemsPrice);
tvTotalNoOfItems.setText(dbList.size() + "");
double totalPrice = 0.0;
for (int i = 0; i < dbList.size(); i++) {
totalPrice += Double.parseDouble(dbList.get(i).getPrice());
}
tvTotalPrice.setText("" + totalPrice);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setItemAnimator(new SlideInUpAnimator());
btnContinueShopping = (Button) findViewById(R.id.btnBackToProductActivity);
btnContinueShopping.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent launchCollectionActivity = new Intent(CartActivity.this, CollectionActivity.class);
startActivity(launchCollectionActivity);
finish();
}
});
btnCheckout = (Button) findViewById(R.id.btn_checkout);
btnCheckout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mAdapter.getItemCount() == 0){
Toast.makeText(CartActivity.this,"Your cart is empty",Toast.LENGTH_SHORT).show();
}
else {
Intent launchCheckoutActivity = new Intent(CartActivity.this, CheckoutActivity.class);
startActivity(launchCheckoutActivity);
} }
});
}
@Override
public void dataChanged() {
tvTotalNoOfItems.setText(dbList.size() + "");
double totalPrice = 0.0;
for (int i = 0; i < dbList.size(); i++) {
totalPrice += Double.parseDouble(dbList.get(i).getPrice());
}
tvTotalPrice.setText("" + totalPrice);
}
}
下面是购物车适配器:
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder> {
public interface OnCartDataChangeListener{
public void dataChanged();
}
private OnCartDataChangeListener listener;
private List<ProductView.Data> productData = Collections.emptyList();
static List<ProductModel> productModelList;
static Context context;
DatabaseHandler mDatabaseHandler;
public CartAdapter(Context context, List<ProductModel> dbList, OnCartDataChangeListener listener ){
this.productModelList = new ArrayList<ProductModel>();
this.context = context;
this.productModelList = dbList;
mDatabaseHandler = new DatabaseHandler( context );
this.listener = listener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View cartListView = inflater.inflate(R.layout.list_item_cart, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(context,cartListView);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.tvProductName.setText(productModelList.get(position).getTitle());
holder.tvProductPrice.setText(productModelList.get(position).getPrice());
Glide
.with(context)
.load(productModelList.get(position).getImageUrl())
.placeholder(R.drawable.placeholder_loading)
.into(holder.imgProduct);
holder.tvSize.setText(productModelList.get(position).getSize());
holder.tvProductQuantity.setText(Integer.toString(productModelList.get(position).getQuantity()));
holder.tvColor.setText(productModelList.get(position).getColor());
holder.imgDelete.setClickable(true);
holder.imgDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String idForDelete = String.valueOf(productModelList.get(position).getVariantId());
mDatabaseHandler.deleteARow(idForDelete);
productModelList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,productModelList.size());
CartActivity.dbList = productModelList;
listener.dataChanged();
}
});
}
@Override
public int getItemCount() {
return productModelList.size();
}
public void Refresh(ArrayList<ProductModel> datas) {
this.productModelList.clear();
this.productModelList.addAll(datas);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvProductName, tvProductPrice, tvProductQuantity, tvColor,
tvSize;
ImageView imgProduct;
ImageButton imgDelete;
Context context;
public ViewHolder(Context mContext, View itemView) {
super(itemView);
this.tvProductName = (TextView) itemView.findViewById(R.id.tv_cart_product_name);
this.tvProductPrice = (TextView) itemView.findViewById(R.id.tv_cart_product_price);
this.tvProductQuantity = (TextView) itemView.findViewById(R.id.tv_cart_product_Quantity);
this.imgProduct = (ImageView) itemView.findViewById(R.id.img_cart_item_product);
this.tvColor = (TextView) itemView.findViewById(R.id.tv_color);
this.tvSize = (TextView) itemView.findViewById(R.id.tv_size);
this.imgDelete = (ImageButton) itemView.findViewById(R.id.img_cart_delete);
// store the context ///
this.context = mContext;
}
}
这个片段来自我在按下addToCart按钮时获得产品的上一个活动:
btn_addToCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String title = tv_productName.getText().toString();
String price = tv_productPrice.getText().toString();
String status = tv_productStatus.getText().toString();
String imageUrl = productImageList.get(0);
String productColor = String.valueOf(sp_productColor.getSelectedItem());
String productSize = String.valueOf(sp_productSize.getSelectedItem());
String productQuantity = String.valueOf(tv_productQuantity.getText());
final String productId = response.data().node().asProduct().id();
final String variantId = response.data().node().asProduct().variants().edges().get(0).node().id();
// save into database
helper = new DatabaseHandler(ProductDetailActivity.this);
helper.insertIntoDB(variantId, title, price, imageUrl, status, productSize, productQuantity, productColor);
// display snackbar to navigate to cart activity
Snackbar.make(view, R.string.snackbar_text, Snackbar.LENGTH_LONG)
.setAction(R.string.snackbar_action, new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent launchCartActivity = new Intent(ProductDetailActivity.this, CartActivity.class);
// adding the first product and its first variant to the cart
launchCartActivity.putExtra("product_id", productId);
launchCartActivity.putExtra("variant_id", variantId);
startActivity(launchCartActivity);
finish();
}
}).show();
}
});
答案 0 :(得分:2)
你应该申请支票。如果购物车中已存在该商品,则仅增加数量 试试吧。
private boolean isAlreadyInCart(int targetItemId) {
boolean isAlreadyInCart = false;
for (int i = 0; i < itemIds.length; i++) {
if (targetItemId == itemIds[i]) {
isAlreadyInCart = true;
break;
}
}
return isAlreadyInCart;
}
现在请像这样调用这个方法。
if (!isAlreadyInCart(itemId)) {
// TODO: add item to cart
} else {
// TODO: increase quantity
}