英文:
How to avoid duplicate items in an ArrayList in Android Studio?
问题
public class AdapterProductUser extends RecyclerView.Adapter<AdapterProductUser.HolderProductUser> implements Filterable {
// ... (Other parts of the adapter)
@Override
public void onBindViewHolder(@NonNull HolderProductUser holder, int position) {
// ... (Previous code)
// Get the quantity from the EditText
int selectedQuantity = Integer.parseInt(holder.quantityEt.getText().toString().trim());
// Handle the addToCart button click
holder.addToCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (selectedQuantity == 0) {
holder.quantityEt.setError("Please enter a quantity");
return;
}
// ... (Other code)
// Update the existing item's quantity in the cart
if (isProductInCart(productId)) {
updateCartItemQuantity(productId, selectedQuantity);
} else {
// Add the new item to the cart
addToCart(productId, title, priceEach, totalPrice, quantity);
}
dialog.dismiss();
}
});
}
// Check if the product is already in the cart
private boolean isProductInCart(String productId) {
// Implementation for checking if the product is in the cart
// Return true if the product is found, false otherwise
}
// Update the quantity of an existing item in the cart
private void updateCartItemQuantity(String productId, int newQuantity) {
// Implementation for updating the quantity of an existing item in the cart
}
// ... (Other methods)
}
public class ShopDetailsActivity extends AppCompatActivity {
// ... (Other parts of the activity)
private void submitOrder() {
// ... (Previous code)
// Loop through cart items and add them to the order
for (int i = 0; i < cartItemList.size(); i++) {
String pId = cartItemList.get(i).getpId();
String quantity = cartItemList.get(i).getQuantity();
// Use the productId and quantity to add the item to the order
// Add the item details to the order using pId and quantity
// ...
}
// ... (Rest of the code)
}
// ... (Other methods)
}
Please note that the provided code snippets are only meant to give you an idea of how to address the issues you've mentioned. You should adapt and integrate these changes into your existing codebase according to your application's architecture and requirements.
英文:
I am trying to develop a grocery delivery app. The user selects a store and then adds some product to the cart and then places the order. However I am having a problem, when the user adds the same product to the cart the product gets duplicated. For example if the user adds a soap of quantity 5 and then again adds the same soap of quantity 10, then the product in the cart is duplicated i.e seperate quantities of 5 and 10. What I want is if the user adds the same product then only the quantity should change and not duplicate the whole item. Furthermore, when the order is placed, the only the quantity 10 is placed in the order but the price is of 15 (i.e 5+10). I believe this is because the product id is same in both cases and therefore they are duplicated in the cart and this is why I want that when user adds the same product to cart, only the quantity should change. Here is my code, I have removed a lot of code from this question to make it as simple as possible, the full code is way too long.
Note: Please see the addToCart button, I think the problem lies in there
AdapterProductUser.java
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
public class AdapterProductUser extends RecyclerView.Adapter<AdapterProductUser.HolderProductUser> implements Filterable {
private Context context;
public ArrayList<ModelProduct> productsist, filterList;
private FilterProductUser filter;
public AdapterProductUser(Context context, ArrayList<ModelProduct> productsist) {
this.context = context;
this.productsist = productsist;
this.filterList = productsist;
}
@NonNull
@Override
public HolderProductUser onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
/*inflate layout*/
View view = LayoutInflater.from(context).inflate(R.layout.row_product_user,parent,false);
return new HolderProductUser(view);
}
@Override
public void onBindViewHolder(@NonNull HolderProductUser holder, int position) {
/*get data*/
final ModelProduct modelProduct = productsist.get(position);
String discountAvailable = modelProduct.getDiscountAvailable();
String discountNote = modelProduct.getDiscountNote();
String discountPrice = modelProduct.getDiscountPrice();
String productCategory = modelProduct.getProductCategory();
String originalPrice = modelProduct.getOriginalPrice();
String productDescription = modelProduct.getProductDescription();
String productTitle = modelProduct.getProductTitle();
String productQuantity = modelProduct.getProductQuantity();
String productId = modelProduct.getProductId();
String timestamp = modelProduct.getTimestamp();
String productIcon = modelProduct.getProductIcon();
/*set data*/
holder.titleTv.setText(productTitle);
holder.discountedNoteTv.setText(discountNote);
holder.descriptionTv.setText(productDescription);
holder.originalPriceTv.setText("Rs "+originalPrice);
holder.discountedPriceTv.setText("Rs "+discountPrice);
}
// Some more code here
addToCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (quantityEt.getText().toString().trim().equals("0") || quantityEt.getText().toString().trim().isEmpty()){
quantityEt.setError("Please enter a quantity");
return;
}
String title = titleTv.getText().toString().trim();
String priceEach = price;
String totalPrice = finalPriceTv.getText().toString().trim().replace("Rs ","");
// Double d = Double.parseDouble(quantityEt.getText().toString().trim());
// int integer = d.intValue();
String quantity = quantityEt.getText().toString().trim();
//String quantity = Integer.toString(integer);
/*add to db (SQLite)*/
addToCart(productId, title, priceEach, totalPrice, quantity);
dialog.dismiss();
}
});
}
private int itemId = 1;
private void addToCart(String productId, String title, String priceEach, String price, String quantity) {
itemId++;
EasyDB easyDB = EasyDB.init(context,"ITEMS_DB")
.setTableName("ITEMS_TABLE")
.addColumn(new Column("Item_Id", new String[]{"text","unique"}))
.addColumn(new Column("Item_PID", new String[]{"text","not null"}))
.addColumn(new Column("Item_Name", new String[]{"text","not null"}))
.addColumn(new Column("Item_Price_Each", new String[]{"text","not null"}))
.addColumn(new Column("Item_Price", new String[]{"text","not null"}))
.addColumn(new Column("Item_Quantity", new String[]{"text","not null"}))
.doneTableColumn();
Boolean b = easyDB.addData("Item_Id",itemId)
.addData("Item_PID",productId)
.addData("Item_Name",title)
.addData("Item_Price_Each",priceEach)
.addData("Item_Price",price)
.addData("Item_Quantity",quantity)
.doneDataAdding();
Toast.makeText(context, "Added to cart...", Toast.LENGTH_SHORT).show();
/*update cart count*/
((ShopDetailsActivity)context).cartCount();
}
@Override
public int getItemCount() {
return productsist.size();
}
@Override
public Filter getFilter() {
if (filter == null){
filter = new FilterProductUser(this,filterList);
}
return filter;
}
class HolderProductUser extends RecyclerView.ViewHolder{
/*ui views*/
private ImageView productIconIv, nextIv;
private TextView discountedNoteTv, titleTv, descriptionTv, addToCartTv,
discountedPriceTv, originalPriceTv;
public HolderProductUser(@NonNull View itemView) {
super(itemView);
productIconIv = itemView.findViewById(R.id.productIconIv);
nextIv = itemView.findViewById(R.id.nextIv);
discountedNoteTv = itemView.findViewById(R.id.discountedNoteTv);
titleTv = itemView.findViewById(R.id.titleTv);
addToCartTv = itemView.findViewById(R.id.addToCartTv);
descriptionTv = itemView.findViewById(R.id.descriptionTv);
discountedPriceTv = itemView.findViewById(R.id.discountedPriceTv);
originalPriceTv = itemView.findViewById(R.id.originalPriceTv);
}
}
}
<!-- end snippet -->
ShopDetailsActivty.java
Note: Here please see the cartCount and submitOrder methods, I think the problem lies in there.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
public class ShopDetailsActivity extends AppCompatActivity {
/*Declare UI Views*/
private ArrayList<ModelProduct> productsList;
private AdapterProductUser adapterProductUser;
/*cart*/
public ArrayList<ModelCartItem> cartItemList;
private AdapterCartItem adapterCartItem;
AlertDialog dialog;
private EasyDB easyDB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_shop_details);
// UI initialization here
loadMyInfo();
loadShopDetails();
loadShopProducts();
loadReviews(); /*avg rating, set on ratingbar*/
/*declare it in class level and init in onCreate*/
easyDB = EasyDB.init(this,"ITEMS_DB")
.setTableName("ITEMS_TABLE")
.addColumn(new Column("Item_Id", new String[]{"text","unique"}))
.addColumn(new Column("Item_PID", new String[]{"text","not null"}))
.addColumn(new Column("Item_Name", new String[]{"text","not null"}))
.addColumn(new Column("Item_Price_Each", new String[]{"text","not null"}))
.addColumn(new Column("Item_Price", new String[]{"text","not null"}))
.addColumn(new Column("Item_Quantity", new String[]{"text","not null"}))
.doneTableColumn();
/*each shop have its own products and orders so if the user add items to cart and go back and open cart in different shop then cart should be different*/
/*so delete cart data whenever user open this activity*/
deleteCartData();
cartCount();
cartBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*show cart dialog*/
showCartDialog();
}
});
public void cartCount(){
/*keep this method public so we can access it in adapter*/
/*get cart coont*/
int count = easyDB.getAllData().getCount();
if (count <= 0 ){
/*cart is empty*/
cartCountTv.setVisibility(View.GONE);
}
else {
/*have some item in cart, show cartCountTv and set count*/
cartCountTv.setVisibility(View.VISIBLE);
cartCountTv.setText(""+count); /*concatenate with string, because we can set integer in textview*/
}
}
// Some more code here
/*dialog*/
AlertDialog.Builder builder = new AlertDialog.Builder(this);
/*set view to dialog*/
builder.setView(view);
shopNameTv.setText(shopName);
EasyDB easyDB = EasyDB.init(this,"ITEMS_DB")
.setTableName("ITEMS_TABLE")
.addColumn(new Column("Item_Id", new String[]{"text","unique"}))
.addColumn(new Column("Item_PID", new String[]{"text","not null"}))
.addColumn(new Column("Item_Name", new String[]{"text","not null"}))
.addColumn(new Column("Item_Price_Each", new String[]{"text","not null"}))
.addColumn(new Column("Item_Price", new String[]{"text","not null"}))
.addColumn(new Column("Item_Quantity", new String[]{"text","not null"}))
.doneTableColumn();
/*get all records from db*/
Cursor res = easyDB.getAllData();
while (res.moveToNext()){
String id = res.getString(1);
String pId = res.getString(2);
String name = res.getString(3);
String price = res.getString(4);
String cost = res.getString(5);
String quantity = res.getString(6);
allTotalPrice = allTotalPrice + Double.parseDouble(cost);
ModelCartItem modelCartItem = new ModelCartItem(
""+id,
""+pId,
""+name,
""+price,
""+cost,
""+quantity
);
cartItemList.add(modelCartItem);
}
/*place order*/
checkoutBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*first validate delivery address*/
if (myLatitude.equals("") || myLatitude.equals("null") || myLongitude.equals("") || myLongitude.equals("null")){
/*user did not enter address in profile*/
Toast.makeText(ShopDetailsActivity.this, "Error: Please enter your address in your profile before placing order...", Toast.LENGTH_LONG).show();
return; /*don't proceed further*/
}
if (myPhone.equals("") || myPhone.equals("null")){
/*user did not enter phone in profile*/
Toast.makeText(ShopDetailsActivity.this, "Error: Please enter your phone number in your profile before placing order...", Toast.LENGTH_LONG).show();
return; /*don't proceed further*/
}
if (cartItemList.size() == 0){
/*cart list is empty*/
Toast.makeText(ShopDetailsActivity.this, "Error: Your cart is empty", Toast.LENGTH_LONG).show();
return;
}
submitOrder();
}
});
}
private void submitOrder() {
/*show progress dialog*/
progressDialog.setMessage("Placing order...");
progressDialog.show();
/*for order id and order time*/
final String timestamp = ""+System.currentTimeMillis();
String cost = allTotalPriceTv.getText().toString().trim().replace("Rs ",""); /*remove Rs if contains*/
/*add latitude, longitude of user to each order | delete previous orders from firebase or add manually to them*/
/*setup order data*/
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("orderId",""+timestamp);
hashMap.put("orderTime",""+timestamp);
hashMap.put("orderStatus","In Progress"); /*In Progress/Completed/Cancelled*/
hashMap.put("orderCost",""+cost);
hashMap.put("orderBy",""+firebaseAuth.getUid());
hashMap.put("orderTo",""+shopUid);
hashMap.put("deliveryFee",""+deliveryFee);
hashMap.put("latitude",""+myLatitude);
hashMap.put("longitude",""+myLongitude);
if (isPromoCodeApplied){
hashMap.put("discount",""+promoPrice);
}
else {
hashMap.put("discount","0");
}
/*add to db*/
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users").child(shopUid).child("Orders");
ref.child(timestamp).setValue(hashMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
/*order info added now add order items*/
for (int i=0; i<cartItemList.size(); i++){
String pId = cartItemList.get(i).getpId();
String id = cartItemList.get(i).getId();
String cost = cartItemList.get(i).getCost();
String name = cartItemList.get(i).getName();
String price = cartItemList.get(i).getPrice();
String quantity = cartItemList.get(i).getQuantity();
HashMap<String,String> hashMap1 = new HashMap<>();
hashMap1.put("pId",pId);
hashMap1.put("name",name);
hashMap1.put("cost",cost);
hashMap1.put("price",price);
hashMap1.put("quantity",quantity);
int countA= Collections.frequency(cartItemList, pId);
Toast.makeText(ShopDetailsActivity.this, ""+countA, Toast.LENGTH_SHORT).show();
ref.child(timestamp).child("Items").child(pId).setValue(hashMap1);
}
progressDialog.dismiss();
deleteCartData();
dialog.dismiss();
cartCount();
Toast.makeText(ShopDetailsActivity.this, "Order Placed Successfully...", Toast.LENGTH_SHORT).show();
prepareNotificationMessage(timestamp);
/*after placing order open order details page*/
/*open order details, we need two keys there, orderId and orderTo*/
// Intent intent = new Intent(ShopDetailsActivity.this, OrderDetailsUsersActivity.class);
// intent.putExtra("orderTo",shopUid);
// intent.putExtra("orderId",timestamp);
// startActivity(intent);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
/*failed to place order*/
progressDialog.dismiss();
Toast.makeText(ShopDetailsActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
<!-- end snippet -->
答案1
得分: 1
我对EasyDb库不太熟悉,但肯定它不会自动检查重复项。
在你的addToCart
函数中,你添加了以下代码部分:
Boolean b = easyDB.addData("Item_Id",itemId)
.addData("Item_PID",productId)
.addData("Item_Name",title)
.addData("Item_Price_Each",priceEach)
.addData("Item_Price",price)
.addData("Item_Quantity",quantity)
.doneDataAdding();
这将新项目添加到数据库,但你没有添加任何逻辑来检查项目是否已经存在于数据库中。此外,通常是insert
数据,而不是更新。因此,我的建议是,如果你已经有一个购物车项目的ArrayList,你可以编写逻辑来检查项目是否存在于ArrayList中。否则,你需要首先向数据库发出查询,然后返回结果,再制定自己的逻辑来检查项目是否在数据库中存在。如果存在,你应该使用新数量来update
数据库,否则就insert
新项目。
英文:
I'm not familiar with EasyDb library, but for sure it doesn't check for duplication automatically
in your addToCart
function you added this part of code
Boolean b = easyDB.addData("Item_Id",itemId)
.addData("Item_PID",productId)
.addData("Item_Name",title)
.addData("Item_Price_Each",priceEach)
.addData("Item_Price",price)
.addData("Item_Quantity",quantity)
.doneDataAdding();
which adds the new item to the database however you didn't add any logic to check if the item already exists in the database. Furthermore, you usually insert
data NOT UPDATING. So my suggestion is if you already have an ArrayList of the items in the cart you can make logic to check if the item exists in the ArrayList. Otherwise, you have to make a query to the database first and return the result and then make your own logic to check if the item exists in the database or not. If yes so you should update
the database with the new number otherwise insert
the new item.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论