Alex Mamo
Alex Mamo

Reputation: 138824

How to add a specific key with a specific value in a firebase database with Android?

I have a realtive simple Firebase database, in which i have 2 models. A ListModel and a UserModel. In my Lists, i'm using push() method to generate unique ids. Each unique id i want to be added as a key and "true" as it's value under Users/gmail@gmail,com/Lists. When i add the first list, the database looks like this:

enter image description here

And everything works fine, but when i try to add another one, the database looks like this: enter image description here

In Users/gmail@gmail,com/Lists, the first one is overwritten by the second insert. How can i add the specific id and the specific value, as a new item as shown below?

enter image description here

And this is my code:

final UserModel um = new UserModel();
um.setUserEmail("gmail@gmail,com");
userDatabaseReference.setValue(um);

ListModel lm = new ListModel();
lm.setListName(listName);
listKeyDatabaseReference = listDatabaseReference.push();
listKey = listKeyDatabaseReference.getKey();
listKeyDatabaseReference.setValue(lm);

listDatabaseReference.child(listKey).child("Users").child("gmail@gmail,com").setValue("true");
userDatabaseReference.child("gmail@gmail,com").child("Lists").child(listKey).setValue("true");

Thanks in advance!

Upvotes: 2

Views: 7662

Answers (1)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363667

Check the official doc:

For basic write operations, you can use setValue() to save data to a specified reference, replacing any existing data at that path.

Your problem is here:

userDatabaseReference.setValue(um);

In this way you are overriding all children in the userDatabaseReference path.
It means that the first record in Users/gmail@gmail,com/Lists is just deleted when you are adding the second one.

Before using the

userDatabaseReference.setValue(um);

you can check if the record exists.
If doesn't exist use the setValue to add the user-model with all its data.
If it exists, just skip this step and add the data in the lists path inside the same user.

Upvotes: 2

Related Questions