0

Newbie to Firebase DB. Below is the structure of my DB:

    Cart-List
        |
        |-UserCarts
            |
            |- 2020-11-11  ( using dateformat :yyyy-MM-dd)
            |     |
            |     | -items
            |          |- productCode
            |          |- price 
            |- 

  1. create the node as follows:

    FirebaseDatabase.getInstance().getReference().child("Cart-List").child("UserCarts")

  2. How to add a new node ( say 2020-11-11) under UserCarts?

    Before adding this new node, is there a way to check if this node is created?

This will allow me to look for items by date easily. Maybe this will reduce the compute time thus incur fewer charges?

Thanks

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
MilkBottle
  • 4,242
  • 13
  • 64
  • 146

1 Answers1

0

When you are using the following reference:

FirebaseDatabase.getInstance().getReference().child("Cart-List").child("UserCarts")

It means that you creating a schema that looks like this:

Firebase-root
  |
  --- Cart-List
        |
        --- UserCarts

If you need to write data at a lower level in your tree, you need to add a few more .child() calls. Assuming you want to write data under the items node, the reference should look like this:

val itemsRef = FirebaseDatabase.getInstance().getReference()
    .child("Cart-List")
    .child("UserCarts")
    .child("2020-11-11")
    .child("items");

One thing to remember, the keys in Firebase are always Strings. If you want to store a Date is more convenient to store it as a Timestamp. So it would be more helpful to add the Timestamp as a property of the object, as explained in my answer from the following post:

Before adding this new node, is there a way to check if this node is created?

If want to check if a node exists, you need to attach a listener, as in the following lines of code:

val valueEventListener = object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        if(dataSnapshot.exists()) {
            //Do what you need to do
        }
    }

    override fun onCancelled(databaseError: DatabaseError) {
        Log.d("TAG", databaseError.getMessage()) //Don't ignore potential errors!
    }
}
itemsRef.addListenerForSingleValueEvent(valueEventListener)

And for Java users:

ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.exists()) {
            //Do what you need to do
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
    }
};
itemsRef.addListenerForSingleValueEvent(valueEventListener);
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193