简体   繁体   中英

Android Studio Java: How can I update my quantity if the product already exist's in my Cart Activity?

I am facing an issue which is, I did not know how to update the product quantity where the product already exist in my cart activity. I am trying to retrieve my data from firebase, but not able to do so.

Here is my code:

private void addToCart() {
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User Type").child(firebaseAuth.getUid());
    databaseReference
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                            if (dataSnapshot.child(firebaseAuth.getUid()).child("Cart").child(productID).exists()){
                                //update to firebase
                                String addedQty1 = "" + snapshot.child("addedQuantity").getValue();
                                int getQty = Integer.parseInt(addedQty1);
                                int currentQty = Integer.parseInt(addedQty);

                                int newAddedQty = getQty + currentQty;

                                String addedNewQty = String.valueOf(newAddedQty);

                                HashMap<String, Object> hashMap1 = new HashMap<>();
                                hashMap1.put("addedQuantity", "" + addedNewQty);

                                DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User Type");
                                databaseReference.child(firebaseAuth.getUid()).child("Cart").child(productID).updateChildren(hashMap1)
                                        .addOnSuccessListener(new OnSuccessListener<Void>() {
                                            @Override
                                            public void onSuccess(Void aVoid) {
                                                //updated
                                                progressDialog.dismiss();
                                                Toast.makeText(ViewProductDetails.this, "Added successfully.", Toast.LENGTH_SHORT).show();
                                            }
                                        })
                                        .addOnFailureListener(new OnFailureListener() {
                                            @Override
                                            public void onFailure(@NonNull Exception e) {
                                                //failed to update
                                                progressDialog.dismiss();
                                                Toast.makeText(ViewProductDetails.this, "" + e.getMessage(), Toast.LENGTH_LONG).show();
                                            }
                                        });
                            } else {
                                //Add to firebase
                                final String timestamp = "" + System.currentTimeMillis();

                                HashMap<String, Object> hashMap = new HashMap<>();
                                hashMap.put("cartID", "" + timestamp);
                                hashMap.put("accountID", "" + accountID);
                                hashMap.put("productID", "" + productID);
                                hashMap.put("orderFrom", "" + shopName);
                                hashMap.put("discountNote", "" + discountNote);
                                hashMap.put("originalPrice", "" + oriPrice);
                                hashMap.put("discountPrice", "" + discountedPrice);
                                hashMap.put("price", "" + price);
                                hashMap.put("productTitle", "" + productTitle);
                                hashMap.put("productCategory", "" + category);
                                hashMap.put("productSize", "" + size);
                                hashMap.put("productQuantity", "" + availableQty);
                                hashMap.put("addedQuantity", "" + addedQty);

                                //add to firebase
                                DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User Type");
                                databaseReference.child(firebaseAuth.getUid()).child("Cart").child(productID).setValue(hashMap)
                                        .addOnSuccessListener(new OnSuccessListener<Void>() {
                                            @Override
                                            public void onSuccess(Void aVoid) {
                                              
                                                progressDialog.dismiss();
                                                Toast.makeText(ViewProductDetails.this, "Added successfully.", Toast.LENGTH_SHORT).show();
                                                
                                            }
                                        })
                                        .addOnFailureListener(new OnFailureListener() {
                                            @Override
                                            public void onFailure(@NonNull Exception e) {
                                                //failed to update
                                                progressDialog.dismiss();
                                                Toast.makeText(ViewProductDetails.this, "" + e.getMessage(), Toast.LENGTH_LONG).show();
                                            }
                                        });
                            }
                        }
                    }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {

                }
            });

}

I have shared the code snippet where "else" statement works fine whereas "if" statement is failed to run. Hope anyone can help me. I really appreciate it!

Your basic solution should look like this pseudocode:

if (product already in cart) {
  get current product count from cart
  increment product count
  store new count back in cart
}

That is one test and three actions. Check that all four are present and that all four work. If you can, it is better to test them separately so you can isolate errors more easily.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM