1

I'm new to Firebase and I need some help.

I want to insert "Cart" value inside "MCwD6C_-XCZNGWxFLhO" user, "Cart" has "itemName","quantity","itemPrice" fields.

I tried a lot of ways still can't do it.

this is my current firebase structure

{
   -User
        -MCwD6C_-XCZNGWxFLhO
           email:testing@gmail.com
           username:testing
}

I want to insert new data become like this

{
  -User
       -MCwD6C_-XCZNGWxFLhO
           email:testing@gmail.com
           username:testing
           -Cart
              itemName:a
              itemPrice:66
}
Mihodi Lushan
  • 670
  • 5
  • 24

2 Answers2

1

You need the key to update data,

To get key:

String key;

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference()
                .child("User");

Query query = databaseReference.orderByChild("username").equalTo("testing");

query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for (DataSnapshot snapShot : dataSnapshot.getChildren()) {
                    key = snapShot.getKey(); //Key
                }

            }

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

To add date

HashMap<String, Object> map = new HashMap<>();
map.put("itemName", "a");
map.put("itemPrice", "66");

databaseReference.child(key).child("Cart").updateChildren(map);

Marsad
  • 859
  • 1
  • 14
  • 35
0

If you have the key -MCwD6C_-XCZNGWxFLhO saved, you can just update the value using setValue(newValue). Check this reference for more. For example, let's say you have done mDatabase.child("User").child(yourKey).setValue(yourObject); where yourObject has no Cart object or the Cart object is null. When you have the Cart object ready in yourObject and you want to push the value, do the same thing again and this time your firebase data will be updated.

Mihodi Lushan
  • 670
  • 5
  • 24
  • how can I get the key -MCwD6C_-XCZNGWxFLhO? – Goze Sim Goze Aug 10 '20 at 05:26
  • The problem here I understand is the structure. You shouldn't have a dependency to auto-generated keys. Since you have a list of users, you should have users ids under user tag and then you put the value. also since you are updating the values, I guess you won't need a list of data in one user node. In that case, you can avoid this id retrieval. https://stackoverflow.com/a/37606379/5339146 check this reference if you really need to loop through the keys. – Mihodi Lushan Aug 10 '20 at 05:38