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);