Search code examples
firebaseloopshashmapiterationsequential

Push HashMap Values Into Firebase Under The Same Node


I am trying to loop through a HashMap and enter the data into the same node, however the code is pushing data into new nodes.

    // Iterate Through HashMap
    for (Map.Entry<String, String> entry : namePhoneMap.entrySet()) {

        String key = entry.getKey();
        String value = entry.getValue();

        fbDatabaseRefPhone.push().child("name").setValue(value);
        fbDatabaseRefPhone.push().child("phone_number").setValue(key);


    }

Basically I want bot the name and phone number to be pushed into the same random node. However it is pushing them into different nodes.


Solution

  • push() always generates a new random key every time you call it. Just call it once and provide a single set of data to write all at the same time at new DatabaseReference it returns:

    HashMap<String, Object> data = new HashMap<>();
    data.put("name", value)
    data.put("phone_number", key);
    DatabaseReference child = fbDatabaseRefPhone.push();
    child.setValue(data);