Alex
Alex

Reputation: 183

How to add a new child without over-writing other children

I am trying to add a new child to the below in my database but every time I add a new child the others are overwritten.

enter image description here

I'm aware setValue() will overwrite children. I don't want to use Push() as this will create another id which I don't want as I want users to be able to go into the database and add a new userID:true manually.

mDatabase = FirebaseDatabase.getInstance().getReference("readUsers")

HashMap<String, String> readUser = new HashMap<>();
                            readUser.put(userId, "true");


mDatabase.setValue(readUser).addOnCompleteListener(new OnCompleteListener<Void>() {

Is there another way I add new children without using push()?

Upvotes: 2

Views: 328

Answers (3)

Taslim Oseni
Taslim Oseni

Reputation: 6263

Just use updateChildren() in place of setValue. That's all you need. At the end, your update line would look like this:

mDatabase.updateChildren(readUser).addOnCompleteListener(new OnCompleteListener<Void>() {
    //Your code
}

You can read the docs here.

I hope this helps.. Merry coding!

Upvotes: 1

Peter Haddad
Peter Haddad

Reputation: 80914

You can use updateChildren():

mDatabase = FirebaseDatabase.getInstance().getReference("readUsers")
Map<String, Object> updates = new HashMap<String,Object>();
updates.put(userId, "true");
mDatabase.updateChildren(updates);

From the docs:

Update specific fields

To simultaneously write to specific children of a node without overwriting other child nodes, use the updateChildren() method.

Upvotes: 1

Alex Mamo
Alex Mamo

Reputation: 138824

To solve this, please change the following line of code:

mDatabase.setValue(readUser).addOnCompleteListener(new OnCompleteListener<Void>() {}

to

mDatabase.updateChildren(readUser).addOnCompleteListener(new OnCompleteListener<Void>() {}

See, instead of using setValue() method, I've used DatabaseReference's updateChildren():

Update the specific child keys to the specified values.

Upvotes: 1

Related Questions