Aldridge1991
Aldridge1991

Reputation: 1367

Firebase add new child with specified name

This is my database

enter image description here

I'd like to add new users to database keeping that format. I've tried this:

   //Store data in database
    Firebase usersRef = ref.child("Users");
    Map<String, String> userData = new HashMap<String, String>();

    userData.put("Nombre", name);
    userData.put("Password", pass);
    userData.put("Confirmed", "FALSE");
    userData.put("Email", mail);

    usersRef.setValue(name);
    usersRef = ref.child("Users").child(name);
    usersRef.setValue(userData);

The problem is whenever I add a new user, the previous one is overwritten.

Upvotes: 18

Views: 53073

Answers (3)

Roshaan Qurban
Roshaan Qurban

Reputation: 79

This worked for me. I am using model class instead of Hash

mFirebaseDatabase.child(name);
mFirebaseDatabase = mFirebaseDatabase.child(name);
FirebaseDatabase.setValue(name);
FirebaseDatabase.setValue(user);

Upvotes: 2

M-Groups
M-Groups

Reputation: 101

Firebase Database Push

[FirebaseDatabase mydb =][2] FirebaseDatabase.getInstance();
DatabaseReference mDatabase = mydb.getReference().child("Dealers").child(dealerId).child("Stock").child(stockAddDate);

Map<String, String> userData = new HashMap<String, String>();

userData.put("Product_Name", productName);
userData.put("Holding_Stock", holdingStock);
userData.put("Primary_Stock", primaryStock);
mDatabase.push().setValue(userData);

Just use "PUSH" before setValue.

Upvotes: 6

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363627

It happens because you are using:

Firebase usersRef = ref.child("Users");
usersRef.setValue(name);

In this way you will push the value in url/Users removing the previous value.

Check the doc:

Using setValue() will overwrite the data at the specified location, including any child nodes.

To add a new user without removing the previous one , just remove this line:

//usersRef.setValue(name);

In this way you will push the value in url/Users/myName without overriding other values.

Upvotes: 17

Related Questions