How to update multiple values in different nodes simultaneously in firebase?

133
January 20, 2022, at 9:10 PM

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?

Answer 1

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.

Rent Charter Buses Company
READ ALSO
loop or each? or other jQuery solution?

loop or each? or other jQuery solution?

How can I simplify the code below into just one element? Hoe can I avoid repetition for each function?

143
Use custom fonts within expo/Node.js-monorepo with UI Kitten

Use custom fonts within expo/Node.js-monorepo with UI Kitten

I am using this monorepo as a base templateI installed UI Kitten based on the instructions in the UI Kitten documentation

117
How to correctly mock SharedPreferenceLiveData in Unit Test?

How to correctly mock SharedPreferenceLiveData in Unit Test?

I have created LiveData wrapper on Shared Preferences and created a shared preferenceLiveDataWhich then I am using in view model(shown below)

150
How can I use a url parameter(that is a user id &lt;str:pk&gt;) to prepopulate a field in DJANGO form

How can I use a url parameter(that is a user id <str:pk>) to prepopulate a field in DJANGO form

I'm doing a management application with 2 pages: users(clientes) and a user datail page that contains a user payment history(cheques)

152