How to Subtract two different node child values in Firebase Realtime Databse?

我的未来我决定 提交于 2020-04-30 07:19:22

问题


I'm creating a Food ordering app.for that I'm saving the food names into the Food unique ID. So I created Item Details as a node, in this node has shopuniqueID as a child node, in this node has food uniqueID
this ID contains food details such as discount,itemname,price,discount If the User book the foods, which will be saved as below format , If the customer confirms the food order after that user-selected quantity wants to delete from total item quantity, How can I delete two different values which are in the two different nodes?

This is my tried coding

btnorder=findViewById(R.id.qrbillid);
    databaseReference= FirebaseDatabase.getInstance().getReference("User Booking").child(UserID).child(shopid);
    dbrefcheck=FirebaseDatabase.getInstance().getReference("Item Details").child(shopid);

    btnorder.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            databaseReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren())
                    {
                        SelectedItems ui=dataSnapshot1.getValue(SelectedItems.class);
                            final String itemid=ui.getItemid();
                            final String Stritemselectedqty=ui.getItemid();
                            final String name=ui.getItemname();

                            ///////////////////----find the user selection----////////////////////
                            dbrefcheck.addValueEventListener(new ValueEventListener() {
                                @Override
                                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                    for(DataSnapshot dataSnapshot2:dataSnapshot.getChildren())
                                    {
                                        UploadItem uploadItem=dataSnapshot2.getValue(UploadItem.class);
                                        String uploadItemID=uploadItem.getKey();
                                        String StrTotalqty=uploadItem.getQuantity();

                                        if(itemid.equals(uploadItemID))
                                        {
                                         // do the mathematical operation
                                         int totalqty=Integer.valueOf(StrTotalqty);
                                         int selectedqty=Integer.valueOf(Stritemselectedqty);

                                         int finalquality=totalqty-selectedqty;
                                            Toast.makeText(MyBookedItems.this, ""+name+"   ", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }

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

                                }
                            });
                            ///////////////////----find the user selection----////////////////////

                    }

                }

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

                }
            });
        }
    });

回答1:


If We want to do mathematical operations between two node child values, We can't directly do that in Firebase Realtime Database.

  1. Retrieve the value from the Firebase
  2. after that do the modification and again upload it.

    private void updateQuantity(final String itemid, final String selecteditem) {

        Query query4 = dbrefcheck
                .orderByChild("key") //key
                .equalTo(itemid);
    
        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()) {
    
                    String qty=ds.child("quantity").getValue(String.class);
    
                    int total=Integer.valueOf(qty);
                    int sub=Integer.valueOf(selecteditem);
                    int fv=total-sub;
                    String sfv=String.valueOf(fv);
    
                    Map<String, Object> map = new HashMap<>();
                    map.put("quantity", sfv);
                    dbrefcheck.child(itemid).updateChildren(map).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
    
                        }
                    }).addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
    
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
    
                        }
                    });
    
                }
            }
    
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
    
            }
        };
    
        query4.addListenerForSingleValueEvent(valueEventListener);
    
    
    }
    
    private void moveSelectedItemstoOrder(final DatabaseReference fromPath, final DatabaseReference toPath) {
    
       final String th=toPath.push().getKey();
    
        fromPath.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(final DataSnapshot dataSnapshot) {
                toPath.child(th).setValue(dataSnapshot.getValue(), new DatabaseReference.CompletionListener() {
                    @Override
                    public void onComplete(DatabaseError firebaseError, DatabaseReference firebase) {
                        if (firebaseError != null) {
                            Toast.makeText(MyBookedItems.this, "Try again", Toast.LENGTH_SHORT).show();
                        } else {
    
                            StoreBookingDetails(th);
    
                        }
                    }
                });
    
            }
    
            @Override
            public void onCancelled(DatabaseError databaseError) {
    
            }
        });
    }
    
    
    
    private void DeleteValuefromSelectedItems() {
        databaseReference.setValue(null).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
    
            }
        }).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
    
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
    
            }
        });
    }
    
    private void StoreBookingDetails(final String keytostore) {
    
        //////////////////------------retrive data-------------//////////////////////////////some these methods are unnecessary but i remove some code 
    
        savedata(keytostore);
    
        //////////////////------------retrive data-------------//////////////////////////////
    }
    
    private void savedata(String keytostore) {
    
        String status="Order Request";
    
        // shopid ---->
        BookingDetails bd=new BookingDetails(keytostore,currentdate,UserID,subtotal,status,f1,f2,f3,currentTime);
    
        dbbookingDetails.child(keytostore).setValue(bd).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if(task.isSuccessful())
                {
                    DeleteValuefromSelectedItems();
                }else
                {
                    Toast.makeText(MyBookedItems.this, "Check the intenet connection", Toast.LENGTH_SHORT).show();
                }
    
            }
        }).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
    
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
    
            }
        });
    
    /////////////////////////////--------------------/////////////////////////////////
    
        UserBookingDetails ubd=new UserBookingDetails(shopname,shopid,shopphnno,keytostore,UserID,subtotal,currentdate,currentTime,"Order Sent","","");
    
        dbbookingdetailsUser.child(keytostore).setValue(ubd).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
    
            }
        }).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                AlertDialog.Builder adb = new AlertDialog.Builder(MyBookedItems.this);
                adb.setTitle("Booking Successful");
                adb.setPositiveButton("View History", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        startActivity(new Intent(MyBookedItems.this,OrderHistory.class));
                    }
    
                });
                adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
    
                    }
                });
                adb.show();
    
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
    
            }
        });
    


来源:https://stackoverflow.com/questions/60968183/how-to-subtract-two-different-node-child-values-in-firebase-realtime-databse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!