要编写单个数据,您可以使用DatabaseReference上的setValue()方法和您的子Id:
private void writeNewData(String userId, String name, String email) {
User user = new User(name, email);
mDatabase.child("users").child(userId).setValue(user);
}
在您的情况下,您可以执行以下操作:
mDatabase.child( “UID2”)子( “KEY2”)的setValue(yourNewValueOrObject).
如果要更新特定值,则应该更简洁:
mDatabase.child( “UID2”)子( “KEY2”)子( “电子邮件”)的setValue(NEWEMAIL).;
无论如何,我建议你使用自定义类作为POJO(普通旧Java对象),并使用数据库中每个项目的值.例如:
public class User {
public String username;
public String email;
public User() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public User(String username, String email) {
this.username = username;
this.email = email;
}
}
最后要删除数据,您应该以相同的方式使用removeValue()方法.
private void deleteUserData(String userId) {
mDatabase.child("users").child(userId).removeValue();
}
此方法将从数据库中删除整个引用,因此请小心使用它.如果要删除特定字段,则应该向树添加另一个.child()调用.例如,假设我们要从“KEY2”节点中删除电子邮件值:
mDatabase.child( “用户”)子(用户ID).child( “电子邮件”)removeValue().
最后,可能我们想要更新不同数据库节点中的多个字段.在这种情况下,我们应该使用updateChildren()方法和引用和值的映射.
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 postValues = post.toMap();
Map childUpdates = new HashMap<>();
childUpdates.put("/posts/" + key, postValues);
childUpdates.put("/user-posts/" + userId + "/" + key, postValues);
mDatabase.updateChildren(childUpdates);
}
updateChildren方法做什么.是否对给定Map< String,Object>中的每一行调用setValue()作为关键是节点的完整引用和Object的值.