0

I wanted to create a add to cart function inside Firebase, but I'm not quite sure on how to write the if statement for my problems.

I want to achieve a result where when user cart is empty it will create a unique id that will hold all the user item information. If user already have item in their cart, the item can just be added without creating a new unique id.

Below is my Cart database, when user already have item in their cart and they want to add a new item in their cart they can just simply add those item in their cart. The highlight ID is the cart id of the user. I have problem, every time user want to add item into their cart, it keep producing new unique key. Which I don't want it. I want the item to be put under the highlighted id. The current problem I'm having is it keep producing a new id every time user add new item.

enter image description here

AddCart class


     String cart_id;

    private void addCart() {

            if (cart_id != null) {


                Intent intent = getIntent();
                final String cust_id = firebaseAuth.getCurrentUser().getUid();
                final String pid = intent.getStringExtra("pid");
                String keyB = intent.getStringExtra("keyB");
                String name = pname.getText().toString().trim();
                String category = pcategory.getText().toString().trim();
                String price = pprice.getText().toString().trim();
                String size = psize.getSelectedItem().toString().trim();
                String quantity = pquantity.getText().toString().trim();

                String image = intent.getStringExtra("pro_image");

                final Cart cart = new Cart(cart_id, pid, cust_id, keyB, name, price, image, category, quantity, size);
                databaseReference.child("Customer List").child(cust_id).child(pid).setValue(cart) //table and primary key
                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                                                   @Override
                                                   public void onComplete(@NonNull Task<Void> task) {
                                                       if (task.isSuccessful()) {
                                                           databaseReference.child("PS List").child(cust_id).child(pid).setValue(cart).addOnCompleteListener(new OnCompleteListener<Void>() {
                                                               @Override
                                                               public void onComplete(@NonNull Task<Void> task) {

                                                                   if (task.isSuccessful()) {
                                                                       Toast.makeText(getApplicationContext(), "add Successfully", Toast.LENGTH_SHORT).show();
                                                                       AddToCart.super.onBackPressed();
                                                                   }
                                                               }
                                                           });

                                                       }
                                                   }
                                               }
                        );
            }
            else
            {
                final String cart_id = databaseReference.push().getKey();
                Intent intent = getIntent();
                final String cust_id = firebaseAuth.getCurrentUser().getUid();
                final String pid = intent.getStringExtra("pid");
                String keyB = intent.getStringExtra("keyB");
                String name = pname.getText().toString().trim();
                String category = pcategory.getText().toString().trim();
                String price = pprice.getText().toString().trim();
                String size = psize.getSelectedItem().toString().trim();
                String quantity = pquantity.getText().toString().trim();

                String image = intent.getStringExtra("pro_image");

                final Cart cart = new Cart(cart_id, pid, cust_id, keyB, name, price, image, category, quantity, size);
                databaseReference.child("Customer List").child(cust_id).child(cart_id).child(pid).setValue(cart) //table and primary key
                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                                                   @Override
                                                   public void onComplete(@NonNull Task<Void> task) {
                                                       if (task.isSuccessful()) {
                                                           databaseReference.child("PS List").child(cust_id).child(cart_id).child(pid).setValue(cart).addOnCompleteListener(new OnCompleteListener<Void>() {
                                                               @Override
                                                               public void onComplete(@NonNull Task<Void> task) {

                                                                   if (task.isSuccessful()) {
                                                                       Toast.makeText(getApplicationContext(), "add Successfully", Toast.LENGTH_SHORT).show();
                                                                       AddToCart.super.onBackPressed();
                                                                   }
                                                               }
                                                           });

                                                       }
                                                   }
                                               }
                        );
            }
        }

Cart


    public class Cart {

        public String cart_id;
        public String pro_id;
        public String cust_id;
        public String brand_id;
        public String pro_name;
        public String pro_price;
        public String pro_image;
        public String pro_category;
        public String quantity;
        public String size;



        public Cart () {
        }


        public Cart(String cart_id, String pro_id, String cust_id, String brand_id, String pro_name, String pro_price, String pro_image, String pro_category, String quantity, String size) {
            this.cart_id = cart_id;
            this.pro_id = pro_id;
            this.cust_id = cust_id;
            this.brand_id = brand_id;
            this.pro_name = pro_name;
            this.pro_price = pro_price;
            this.pro_image = pro_image;
            this.pro_category = pro_category;
            this.quantity = quantity;
            this.size = size;

        }

baelyn
  • 73
  • 1
  • 1
  • 9
  • https://stackoverflow.com/questions/3386667/query-if-android-database-exists – Ankita Nov 21 '19 at 07:47
  • it would be really helpful if you could see my problem and coding first. Thank you – baelyn Nov 21 '19 at 07:48
  • perform a get ... result == null ? it doesn't exist. – Stultuske Nov 21 '19 at 07:55
  • 1
    It might be a copy-paste artifact from giving us a subsection, but it looks like the cart_id in the if statement is never set so you'll always go over the null path. – Thomas Nov 21 '19 at 08:00
  • @Stultuske how do I write a correct statement if if the user is the new user of my apps. The user will not have the existing id. Does this work too? I'm creating the if else statement because if the user already have the existing cart id then the new added item will add under the existing id, but if the user don't have cart id yet, It will create a new cart id for the user. – baelyn Nov 21 '19 at 08:17
  • @Thomas how do I write a correct statement if if the user is the new user of my apps. The user will not have the existing id. Does this work too? I'm creating the if else statement because if the user already have the existing cart id then the new added item will add under the existing id, but if the user don't have cart id yet, It will create a new cart id for the user. – baelyn Nov 21 '19 at 08:17
  • @baelyn if ( value.isBad()) { throw new MyCustomException("Invalid value: " + value.toString()); } – Stultuske Nov 21 '19 at 08:32

1 Answers1

1

If you want items to be added to the exiting id without creating another one then try the following:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Cart").child("CustomerList");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userId = user.getUid();
String uniqueId = ref.child(userId).push().getKey();

This uniqueId will be the existing id. You can pass it through activities using Intent, then when you want to retrieve data you can do this:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Cart").child("CustomerList").child(userId).child(uniqueId);
ref.addValueEventListener(new ValueEventListener()){...
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • what if the user is the new user of my apps. The user will not have the existing id. Does this work too? I'm creating the if else statement because if the user already have the existing cart id then the new added item will add under the existing id, but if the user don't have cart id yet, It will create a new cart id for the user. – baelyn Nov 21 '19 at 08:14
  • yes it will work, this `String userId = user.getUid();` will retrieve the id of the currently logged in user, every user that logs in will have an id.. and then under is the random id – Peter Haddad Nov 21 '19 at 08:17
  • in your code `WP1RgwZXMdhMTGdPYIubPVnYI2v2` is the user id – Peter Haddad Nov 21 '19 at 08:18
  • how do i customize this code into my coding above in the addCart() function or I have to override it all? – baelyn Nov 21 '19 at 08:23
  • from where did you copy the addCart()? – Peter Haddad Nov 21 '19 at 08:27
  • sorry? Do you need to see my full coding? – baelyn Nov 21 '19 at 08:29
  • in the `addCart()` you declare `String cart_id;` before it which will always be null..since it is always null, it will enter the `else` and will create a new one `final String cart_id = databaseReference.push().getKey();` – Peter Haddad Nov 21 '19 at 08:32
  • btw when I'm implementing this code ` FirebaseUser user = FirebaseAuth.getInstance();` it said that Incompatible types – baelyn Nov 21 '19 at 08:33
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/202782/discussion-between-baelyn-and-peter-haddad). – baelyn Nov 21 '19 at 08:34
  • 1
    it should be `FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser()` – Peter Haddad Nov 21 '19 at 08:35