如何在Android Studio中避免ArrayList中的重复项?

huangapple go评论77阅读模式
英文:

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&lt;AdapterProductUser.HolderProductUser&gt; implements Filterable {
private Context context;
public ArrayList&lt;ModelProduct&gt; productsist, filterList;
private FilterProductUser filter;
public AdapterProductUser(Context context, ArrayList&lt;ModelProduct&gt; 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(&quot;Rs &quot;+originalPrice);
holder.discountedPriceTv.setText(&quot;Rs &quot;+discountPrice);
}
// Some more code here
addToCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (quantityEt.getText().toString().trim().equals(&quot;0&quot;) || quantityEt.getText().toString().trim().isEmpty()){
quantityEt.setError(&quot;Please enter a quantity&quot;);
return;
}
String title = titleTv.getText().toString().trim();
String priceEach = price;
String totalPrice = finalPriceTv.getText().toString().trim().replace(&quot;Rs &quot;,&quot;&quot;);
//                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,&quot;ITEMS_DB&quot;)
.setTableName(&quot;ITEMS_TABLE&quot;)
.addColumn(new Column(&quot;Item_Id&quot;, new String[]{&quot;text&quot;,&quot;unique&quot;}))
.addColumn(new Column(&quot;Item_PID&quot;, new String[]{&quot;text&quot;,&quot;not null&quot;}))
.addColumn(new Column(&quot;Item_Name&quot;, new String[]{&quot;text&quot;,&quot;not null&quot;}))
.addColumn(new Column(&quot;Item_Price_Each&quot;, new String[]{&quot;text&quot;,&quot;not null&quot;}))
.addColumn(new Column(&quot;Item_Price&quot;, new String[]{&quot;text&quot;,&quot;not null&quot;}))
.addColumn(new Column(&quot;Item_Quantity&quot;, new String[]{&quot;text&quot;,&quot;not null&quot;}))
.doneTableColumn();
Boolean b = easyDB.addData(&quot;Item_Id&quot;,itemId)
.addData(&quot;Item_PID&quot;,productId)
.addData(&quot;Item_Name&quot;,title)
.addData(&quot;Item_Price_Each&quot;,priceEach)
.addData(&quot;Item_Price&quot;,price)
.addData(&quot;Item_Quantity&quot;,quantity)
.doneDataAdding();
Toast.makeText(context, &quot;Added to cart...&quot;, 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&lt;ModelProduct&gt; productsList;
private AdapterProductUser adapterProductUser;
/*cart*/
public ArrayList&lt;ModelCartItem&gt; 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,&quot;ITEMS_DB&quot;)
.setTableName(&quot;ITEMS_TABLE&quot;)
.addColumn(new Column(&quot;Item_Id&quot;, new String[]{&quot;text&quot;,&quot;unique&quot;}))
.addColumn(new Column(&quot;Item_PID&quot;, new String[]{&quot;text&quot;,&quot;not null&quot;}))
.addColumn(new Column(&quot;Item_Name&quot;, new String[]{&quot;text&quot;,&quot;not null&quot;}))
.addColumn(new Column(&quot;Item_Price_Each&quot;, new String[]{&quot;text&quot;,&quot;not null&quot;}))
.addColumn(new Column(&quot;Item_Price&quot;, new String[]{&quot;text&quot;,&quot;not null&quot;}))
.addColumn(new Column(&quot;Item_Quantity&quot;, new String[]{&quot;text&quot;,&quot;not null&quot;}))
.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 &lt;= 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(&quot;&quot;+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,&quot;ITEMS_DB&quot;)
.setTableName(&quot;ITEMS_TABLE&quot;)
.addColumn(new Column(&quot;Item_Id&quot;, new String[]{&quot;text&quot;,&quot;unique&quot;}))
.addColumn(new Column(&quot;Item_PID&quot;, new String[]{&quot;text&quot;,&quot;not null&quot;}))
.addColumn(new Column(&quot;Item_Name&quot;, new String[]{&quot;text&quot;,&quot;not null&quot;}))
.addColumn(new Column(&quot;Item_Price_Each&quot;, new String[]{&quot;text&quot;,&quot;not null&quot;}))
.addColumn(new Column(&quot;Item_Price&quot;, new String[]{&quot;text&quot;,&quot;not null&quot;}))
.addColumn(new Column(&quot;Item_Quantity&quot;, new String[]{&quot;text&quot;,&quot;not null&quot;}))
.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(
&quot;&quot;+id,
&quot;&quot;+pId,
&quot;&quot;+name,
&quot;&quot;+price,
&quot;&quot;+cost,
&quot;&quot;+quantity
);
cartItemList.add(modelCartItem);
}
/*place order*/
checkoutBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*first validate delivery address*/
if (myLatitude.equals(&quot;&quot;) || myLatitude.equals(&quot;null&quot;) || myLongitude.equals(&quot;&quot;) || myLongitude.equals(&quot;null&quot;)){
/*user did not enter address in profile*/
Toast.makeText(ShopDetailsActivity.this, &quot;Error: Please enter your address in your profile before placing order...&quot;, Toast.LENGTH_LONG).show();
return; /*don&#39;t proceed further*/
}
if (myPhone.equals(&quot;&quot;) || myPhone.equals(&quot;null&quot;)){
/*user did not enter phone in profile*/
Toast.makeText(ShopDetailsActivity.this, &quot;Error: Please enter your phone number in your profile before placing order...&quot;, Toast.LENGTH_LONG).show();
return; /*don&#39;t proceed further*/
}
if (cartItemList.size() == 0){
/*cart list is empty*/
Toast.makeText(ShopDetailsActivity.this, &quot;Error: Your cart is empty&quot;, Toast.LENGTH_LONG).show();
return;
}
submitOrder();
}
});
}
private void submitOrder() {
/*show progress dialog*/
progressDialog.setMessage(&quot;Placing order...&quot;);
progressDialog.show();
/*for order id and order time*/
final String timestamp = &quot;&quot;+System.currentTimeMillis();
String cost = allTotalPriceTv.getText().toString().trim().replace(&quot;Rs &quot;,&quot;&quot;); /*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&lt;String,String&gt; hashMap = new HashMap&lt;&gt;();
hashMap.put(&quot;orderId&quot;,&quot;&quot;+timestamp);
hashMap.put(&quot;orderTime&quot;,&quot;&quot;+timestamp);
hashMap.put(&quot;orderStatus&quot;,&quot;In Progress&quot;); /*In Progress/Completed/Cancelled*/
hashMap.put(&quot;orderCost&quot;,&quot;&quot;+cost);
hashMap.put(&quot;orderBy&quot;,&quot;&quot;+firebaseAuth.getUid());
hashMap.put(&quot;orderTo&quot;,&quot;&quot;+shopUid);
hashMap.put(&quot;deliveryFee&quot;,&quot;&quot;+deliveryFee);
hashMap.put(&quot;latitude&quot;,&quot;&quot;+myLatitude);
hashMap.put(&quot;longitude&quot;,&quot;&quot;+myLongitude);
if (isPromoCodeApplied){
hashMap.put(&quot;discount&quot;,&quot;&quot;+promoPrice);
}
else {
hashMap.put(&quot;discount&quot;,&quot;0&quot;);
}
/*add to db*/
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference(&quot;Users&quot;).child(shopUid).child(&quot;Orders&quot;);
ref.child(timestamp).setValue(hashMap)
.addOnSuccessListener(new OnSuccessListener&lt;Void&gt;() {
@Override
public void onSuccess(Void aVoid) {
/*order info added now add order items*/
for (int i=0; i&lt;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&lt;String,String&gt; hashMap1 = new HashMap&lt;&gt;();
hashMap1.put(&quot;pId&quot;,pId);
hashMap1.put(&quot;name&quot;,name);
hashMap1.put(&quot;cost&quot;,cost);
hashMap1.put(&quot;price&quot;,price);
hashMap1.put(&quot;quantity&quot;,quantity);
int countA= Collections.frequency(cartItemList, pId);
Toast.makeText(ShopDetailsActivity.this, &quot;&quot;+countA, Toast.LENGTH_SHORT).show();
ref.child(timestamp).child(&quot;Items&quot;).child(pId).setValue(hashMap1);
}
progressDialog.dismiss();
deleteCartData();
dialog.dismiss();
cartCount();
Toast.makeText(ShopDetailsActivity.this, &quot;Order Placed Successfully...&quot;, 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(&quot;orderTo&quot;,shopUid);
//                        intent.putExtra(&quot;orderId&quot;,timestamp);
//                        startActivity(intent);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
/*failed to place order*/
progressDialog.dismiss();
Toast.makeText(ShopDetailsActivity.this, &quot;&quot;+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(&quot;Item_Id&quot;,itemId)
                .addData(&quot;Item_PID&quot;,productId)
                .addData(&quot;Item_Name&quot;,title)
                .addData(&quot;Item_Price_Each&quot;,priceEach)
                .addData(&quot;Item_Price&quot;,price)
                .addData(&quot;Item_Quantity&quot;,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.

huangapple
  • 本文由 发表于 2020年9月28日 10:11:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64095112.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定