Screenshot of my Database in firebase
Here I have a node called products. In that, I have many child nodes. All those nodes have a common value called product stock. I need to update the product stock value of all the nodes inside the product. How can I do that in android studio (Java) because I'm developing a shopping application? Need help.
private void updateStock(String quantity, String availablestock) {
int qty = Integer.parseInt(quantity);
int stk_avl = Integer.parseInt(availablestock);
int stk = stk_avl - qty;
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("ProductStock", "" stk);
//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) {
//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();
}
});
}
The flow is: The user adds the products to the cart. In the cart, I have ordernow button. So when the user clicks order now, the products' quantity in his cart should be subtracted from the product stock value which is in the products node. But when this code runs, for example, assume I have 5 products in the cart, this code is updating product stock for only 1 product (last added product in the cart). How can I make it update all the products?
CodePudding user response:
To be able to update multiple children that exist under a particular node, you have to create a query and use updateChildren method as seen below:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = dbFirebaseDatabase.child("Users");
DatabaseReference productsRef = usersRef.child(shopUid).child("Products");
DatabaseReference additionalUserInfoRef = rootRef.child("AdditionalUserInfo");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = new HashMap<>();
map.put("ProductStock", newValueOfTypeInt);
ds.getRef().updateChildren(map);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
productsRef.addListenerForSingleValueEvent(valueEventListener);
If you want, you can also attach a listener to the .updateChildren(map) to see if something goes wrong.
