0

I'm working in a grocery app. I have a field called product stock in all products. It holds the available stock of a particular product. the flow is user add some products into the cart. when he press the order now button, the quantity of each product should get subracted from product stock and update the resulting stock in product stock field. Below is my code. My problem is if user adds more than 1 product in cart, only the last added product's quantity is getting subracted from stock value and updating that 1 product's value to all the products in cart. It is not updating it's corresponding value. How to make it update it's corresponding value.....

package com.shopping.grocery_ekart.Activities;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.shopping.grocery_ekart.Adapters.AdapterCartItem;
import com.shopping.grocery_ekart.Models.ModelCartItem;
import com.shopping.grocery_ekart.Models.ModelOrderedItem;
import com.shopping.grocery_ekart.R;
import com.shopping.grocery_ekart.category_Constants;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import p32929.androideasysql_library.Column;
import p32929.androideasysql_library.EasyDB;

public class CartActivity extends AppCompatActivity {

    private static final String cod = "Cash on Delivery";
    private static final String op = "Online Payment";

    private ProgressDialog progressDialog;
    private FirebaseAuth firebaseAuth;
    //cart
    private ArrayList<ModelCartItem> cartItemList;
    private AdapterCartItem adapterCartItem;

    private EasyDB easyDB;

    private Dialog dialog1, dialog2;
    private String shopUid, myLatitude, myLongitude, myPhone, shopname;
    public String deliveryFee;
    public TextView sTotalTv, dFeeTv, allTotalPriceTv, shopNameTv, dummy;
    private RecyclerView cartItemsRv;
    private Button checkOutBtn;
    private ImageButton backBtn;

    public int allTotalPrice = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);

        firebaseAuth = FirebaseAuth.getInstance();

        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Please wait");
        progressDialog.setCanceledOnTouchOutside(false);

        shopNameTv = findViewById(R.id.shopNameTv);
        cartItemsRv  = findViewById(R.id.cartItemsRv);
        sTotalTv = findViewById(R.id.sTotalTv);
        dFeeTv = findViewById(R.id.dFeeTv);
        allTotalPriceTv = findViewById(R.id.allTotalPriceTv);
        checkOutBtn = findViewById(R.id.checkOutBtn);
        dummy = findViewById(R.id.dummy);
        backBtn = findViewById(R.id.backBtn);

        shopUid = getIntent().getStringExtra("shopUid");
        myLatitude = getIntent().getStringExtra("latitude");
        myLongitude = getIntent().getStringExtra("longitude");
        myPhone = getIntent().getStringExtra("phone");
        deliveryFee = getIntent().getStringExtra("delivery");
        shopname = getIntent().getStringExtra("shopname");

        dFeeTv.setText("₹" + deliveryFee);
        sTotalTv.setText("₹" +  allTotalPrice);
        allTotalPriceTv.setText("₹" + (allTotalPrice + (deliveryFee.replace("₹", ""))));

        LoadCart();

        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"}))
                .addColumn(new Column("Available_Stock", new String[]{"text", "not null"}))
                .doneTableColumn();

        //each shop have its own products and orders so if user add items to cart and go to andother shop's cart , it should be different
        //so delete cart data whenever user open this activity
        //deleteCartData();
        //cartCount();

        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
                finish();
            }
        });


        //place order
        checkOutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //validate delivery address
                if (myLatitude.equals("") || myLatitude.equals("null") || myLongitude.equals("") || myLongitude.equals("null")) {

                    Toast.makeText(CartActivity.this, "Please enter your address in your profile before placing order... ", Toast.LENGTH_SHORT).show();
                    return;//don't proceed further
                }
                if (myPhone.equals("") || myPhone.equals("null")) {
                    Toast.makeText(CartActivity.this, "Please enter your phone number in your profile before placing order... ", Toast.LENGTH_SHORT).show();
                    return;//don't proceed further
                }
                if (cartItemList.size() == 0) {
                    //cart list is empty
                    Toast.makeText(CartActivity.this, "No item in cart", Toast.LENGTH_SHORT).show();
                    return;//don't proceed further

                }

                if (allTotalPrice<500) {
                    dialog1.show();
                }
                else {
                    dialog2.show();
                }

            }
        });

        dialog1 = new Dialog(this);
        dialog1.setContentView(R.layout.checkout_warning_dialog);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            dialog1.getWindow().setBackgroundDrawable(getDrawable(R.drawable.custom_dialog));
        }
        dialog1.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog1.setCancelable(false); //Optional
        dialog1.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //Setting the animations to dialog

        Button continue_shop = dialog1.findViewById(R.id.continue_shop);

        continue_shop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog1.dismiss();
            }
        });

        dialog2 = new Dialog(this);
        dialog2.setContentView(R.layout.paymentmode_dialog);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            dialog2.getWindow().setBackgroundDrawable(getDrawable(R.drawable.custom_dialog));
        }

        dialog2.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog2.setCancelable(false); //Optional
        dialog2.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //Setting the animations to dialog

        ImageButton backBtn = dialog2.findViewById(R.id.backBtn);
        Button clear = dialog2.findViewById(R.id.clear);
        Button pay_now = dialog2.findViewById(R.id.pay_now);
        Button place_order = dialog2.findViewById(R.id.place_order);
        RadioGroup radioGroup = dialog2.findViewById(R.id.groupradio);
        RadioButton radia_id1 = dialog2.findViewById(R.id.radia_id1);
        RadioButton radia_id2 = dialog2.findViewById(R.id.radia_id2);
        TextView status = dialog2.findViewById(R.id.status);

        radioGroup.clearCheck();

        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                radioGroup.clearCheck();
                pay_now.setVisibility(View.INVISIBLE);
                place_order.setVisibility(View.INVISIBLE);
                status.setVisibility(View.INVISIBLE);
                dialog2.dismiss();
            }
        });
        pay_now.setVisibility(View.INVISIBLE);
        place_order.setVisibility(View.INVISIBLE);
        status.setVisibility(View.INVISIBLE);

        // Uncheck or reset the radio buttons initially

        // Add the Listener to the RadioGroup
        //assert radioGroup != null;
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            // The flow will come here when
            // any of the radio buttons in the radioGroup
            // has been clicked

            // Check which radio button has been clicked
            public void onCheckedChanged(RadioGroup group, int checkedId)
            {
                // Get the selected Radio Button
                RadioButton radia_id2 = dialog2.findViewById(R.id.radia_id2);
                RadioButton radia_id1 = dialog2.findViewById(R.id.radia_id1);

                if (radia_id1.isChecked()) {
                    pay_now.setVisibility(View.VISIBLE);
                    place_order.setVisibility(View.GONE);
                    status.setVisibility(View.VISIBLE);
                    status.setText(op);
                    dummy.setText(op);

                }
                if (radia_id2.isChecked()) {
                    place_order.setVisibility(View.VISIBLE);
                    pay_now.setVisibility(View.GONE);
                    status.setVisibility(View.VISIBLE);
                    status.setText(cod);
                    dummy.setText(cod);

                }

            }
        });

        // Add the Listener to the Submit Button
        pay_now.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                // When submit button is clicked,
                // Ge the Radio Button which is set
                // If no Radio Button is set, -1 will be returned
                int selectedId = radioGroup.getCheckedRadioButtonId();
                if (selectedId == -1) {
                    Toast.makeText(CartActivity.this, "Please select any one option", Toast.LENGTH_SHORT).show();
                }
                else {
                    RadioButton radia_id2 = (RadioButton)radioGroup.findViewById(selectedId);
                    submitOrder();
                    deleteCartData();

                }
            }
        });

        place_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                // When submit button is clicked,
                // Ge the Radio Button which is set
                // If no Radio Button is set, -1 will be returned
                int selectedId = radioGroup.getCheckedRadioButtonId();
                if (selectedId == -1) {
                    Toast.makeText(CartActivity.this, "Please select any one option", Toast.LENGTH_SHORT).show();
                }
                else {
                    RadioButton radia_id1 = (RadioButton)radioGroup.findViewById(selectedId);
                    submitOrder();
                    deleteCartData();

                }
            }
        });

        // Add the Listener to the Submit Button
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                // Clear RadioGroup
                // i.e. reset all the Radio Buttons
                int selectedId = radioGroup.getCheckedRadioButtonId();
                if (selectedId != -1) {
                    radioGroup.clearCheck();
                    pay_now.setVisibility(View.INVISIBLE);
                    place_order.setVisibility(View.INVISIBLE);
                    status.setVisibility(View.INVISIBLE);
                }
                else {
                    Toast.makeText(CartActivity.this, "No option is selected", Toast.LENGTH_SHORT).show();
                }

            }
        });


    }

    private void LoadCart() {

        cartItemList = new ArrayList<>();

        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"}))
                .addColumn(new Column("Available_Stock", 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);
            String availablestock = res.getString(7);

            allTotalPrice = allTotalPrice + Integer.parseInt(cost);

            ModelCartItem modelCartItem = new ModelCartItem(
                    "" + id,
                    "" + pId,
                    "" + name,
                    "" + price,
                    "" + cost,
                    "" + quantity,
                    "" + availablestock
            );

            cartItemList.add(modelCartItem);
        }

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        cartItemsRv.setLayoutManager(mLayoutManager);
        //setup adapter
        adapterCartItem = new AdapterCartItem(this, cartItemList);
        //set to recyclerview
        cartItemsRv.setAdapter(adapterCartItem);

        dFeeTv.setText("₹" + deliveryFee);
        sTotalTv.setText("₹" +  allTotalPrice);
        allTotalPriceTv.setText("₹" + (allTotalPrice + Integer.parseInt(deliveryFee.replace("₹", ""))));

    }

    private void deleteCartData() {
        easyDB.deleteAllDataFromTable(); //delete all records from cart
    }


    String quantity, availablestock;
    String productId;
    private void submitOrder() {
        progressDialog.setMessage("Placing order...");
        progressDialog.show();

        //for order id and order time
        final String timestamp = "" + System.currentTimeMillis();
        String cost = allTotalPriceTv.getText().toString().trim().replace("₹", "");// remove ₹ if contains
        String paystatus = dummy.getText().toString();

        //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("latitude", ""+myLatitude);
        hashMap.put("longitude", ""+myLongitude);
        hashMap.put("PaymentMode", ""+paystatus);

        //add to db
        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++) {
                            productId = 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();
                            quantity = cartItemList.get(i).getQuantity();
                            availablestock = cartItemList.get(i).getAvailablestock();

                            HashMap<String, String> hashMap1 = new HashMap<>();
                            hashMap1.put("pId", productId);
                            hashMap1.put("name", name);
                            hashMap1.put("cost", cost);
                            hashMap1.put("price", price);
                            hashMap1.put("quantity", quantity);
                            hashMap1.put("ProductStock", availablestock);

                            ref.child(timestamp).child("Items").child(productId).setValue(hashMap1);

                        }
                        progressDialog.dismiss();
                        Toast.makeText(CartActivity.this, "Please wait.....", Toast.LENGTH_SHORT).show();

                        prepareNotificationMessage(timestamp);
                        updateStock(quantity, availablestock);

                    }


                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        //failed placing order
                        progressDialog.dismiss();
                        Toast.makeText(CartActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

    }

    private void updateStock(String quantity, String availablestock) {

        int qty = Integer.parseInt(quantity);
        int stk_avl = Integer.parseInt(availablestock);

        HashMap<String, Object> hashMap = new HashMap<>();

        //update to database
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
        reference.child(shopUid).child("Products").child(productId)
                .updateChildren(hashMap)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {

                        for (int i = 0; i < cartItemList.size(); i++) {
                            //reference.orderByChild(productId).equalTo("Products");

                            int stk = stk_avl - qty;
                            productId = cartItemList.get(i).getpId();

                            hashMap.put("ProductStock", ""+stk);
                            reference.child(shopUid).child("Products").child(productId).updateChildren(hashMap);

                        }
                        //update success
                        progressDialog.dismiss();

                        Toast.makeText(CartActivity.this, "Updated...", Toast.LENGTH_SHORT).show();

                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        progressDialog.dismiss();
                        Toast.makeText(CartActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void prepareNotificationMessage(String orderId) {
        //which user place order , send notification to admin
        //prepare data for notification
        String NOTIFICATION_TOPIC = "/topics/" + category_Constants.FCM_TOPIC;
        String NOTIFICATION_TITLE = "New Order "+ orderId;
        String NOTIFICATION_MESSAGE = "Your customer has placed a new order!";
        String NOTIFICATION_TYPE = "NewOrder";

        //prepare json (what and where to send)
        JSONObject notificationJo = new JSONObject();
        JSONObject notificationBodyJo = new JSONObject();
        try {
            //what to send
            notificationBodyJo.put("notificationType", NOTIFICATION_TYPE);
            notificationBodyJo.put("buyerUid", firebaseAuth.getUid());
            notificationBodyJo.put("sellerUid", shopUid);
            notificationBodyJo.put("orderId", orderId);
            notificationBodyJo.put("notificationTitle", NOTIFICATION_TITLE);
            notificationBodyJo.put("notificationMessage", NOTIFICATION_MESSAGE);
            //where to send
            notificationJo.put("to", NOTIFICATION_TOPIC);
            notificationJo.put("data", notificationBodyJo);

        }
        catch (Exception e) {
            Toast.makeText(this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        sendFcmNotification(notificationJo, orderId);
    }

    private void sendFcmNotification(JSONObject notificationJo, String orderId) {
        //send volley request
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", notificationJo, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                //after sending fcm, start order details activity
                //after placing order open order details page
                Intent intent = new Intent(CartActivity.this, OrdersDetailsUsersActivity.class);
                intent.putExtra("orderTo", shopUid);
                intent.putExtra("orderId", orderId);
                intent.putExtra("ProductStock", availablestock);

                startActivity(intent);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //if failed sending fcm, still start order details activity
                // Intent intent = new Intent(ShopDetailsActivity.this, OrdersDetailsUsersActivity.class);
                // intent.putExtra("orderTo", shopUid);
                // intent.putExtra("orderId", orderId);
                //startActivity(intent);
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {

                //put required headers
                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                headers.put("Authorization", "key=" + category_Constants.FCM_KEY);

                return headers;
            }
        };
        //enque the volley request
        Volley.newRequestQueue(this).add(jsonObjectRequest);

    }

}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 2
    If you encounter problems, it's best to create a [MCVE](https://stackoverflow.com/help/mcve) when posting a question. You posted almost **600 (six hundred)** lines of code for this issue. That's a lot for people to parse and try to debug online. Please edit your question and isolate the problem, in that way you increase your chances of being helped. – Alex Mamo Jan 26 '22 at 09:55
  • I think you are looking for a multi-location update. Here's an answer in Swift but it's pretty simple to convert to android [update multiple locations](https://stackoverflow.com/questions/38462074/using-updatechildvalues-to-delete-from-firebase/38466959#38466959) – Jay Jan 27 '22 at 20:29
  • Exactly!!!! I have a node called products under that I have some nodes(each node under product is a product details) as per requirement, I need particular number of nodes to get updated with it's corresponding values. how to convert the thing which is in swift to android .... – e_kart shop Jan 28 '22 at 07:58

0 Answers0