0

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

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);
        }
    }

}

ShopDetailsActivty.java Note: Here please see the cartCount and submitOrder methods, I think the problem lies in there.

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();
                    }
                });
    }

1
  • Before adding to cart, you just check if the item being added is already added or not and if it exists, prompt the user that he has already added it else add the item. Commented Sep 28, 2020 at 3:29

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.