To write single data, you can use the setValue()
method on your DatabaseReference
with your child identifiers:
private void writeNewData(String userId, String name, String email) { User user = new User(name, email); mDatabase.child("users").child(userId).setValue(user); }
In your case, you can do something like: mDatabase.child("UID2").child("KEY2").setValue(yourNewValueOrObject);
If you want to update a specific value, you should be more concise: mDatabase.child("UID2").child("KEY2").child("email").setValue(newEmail);
In any case, I recommend that you use custom classes like POJO (plain old Java object) with the values โโof each of your items in the database. For instance:
public class User { public String username; public String email; public User() {
Finally, to remove data, you must use the removeValue()
method in the same way.
private void deleteUserData(String userId) { mDatabase.child("users").child(userId).removeValue(); }
This method will remove the entire link from your database, so be careful with it. In case you want to delete a specific field, you must add another .child()
call to the tree. For example, say we want to remove the email value from the "KEY2" node: mDatabase.child("users").child(userId).child("email").removeValue();
Finally, there is a case that, perhaps, we want to update several fields in different database nodes. In this case, we should use the updateChildren()
method with a map of links and values.
private void writeNewPost(String userId, String username, String title, String body) { // Create new post at /user-posts/$userid/$postid and at // /posts/$postid simultaneously String key = mDatabase.child("posts").push().getKey(); Post post = new Post(userId, username, title, body); Map<String, Object> postValues = post.toMap(); Map<String, Object> childUpdates = new HashMap<>(); childUpdates.put("/posts/" + key, postValues); childUpdates.put("/user-posts/" + userId + "/" + key, postValues); mDatabase.updateChildren(childUpdates); }
What does the updateChildren
method do. Is setValue ()
call to each line in the specified Map<String, Object>
, which is the key to the full reference to the node and Object value.
You can read more updates and delete data in the official Firebase documentation.