这是我的数据库:
{
"UID1" : {
"KEY" : {
"Name" : "name1",
"Email" : "something1@something.com",
"userid" : "UID1"
}
},
"UID2" : {
"KEY2" : {
"Name" : "name1",
"Email" : "something1@something.com",
"userid" : "UID2"
},
"KEY3" : {
"Name" : "name2",
"Email" : "something2@something.com",
"userid" : "UID2"
},
"KEY4" : {
"Name" : "name3",
"Email" : "something3@something.com",
"userid" : "UID2"
}
}
我想更新和删除数据,例如位于“KEY2”位置的数据。
我怎样才能做到这一点?我还没有在 Android 中尝试过任何代码。
最佳答案
要写入单个数据,您可以使用 setValue()
DatabaseReference
上的方法与您 child 的身份证:
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").child("KEY2").setValue(yourNewValueOrObject);
如果你想更新一个特定的值,你应该更简洁:
mDatabase.child("UID2").child("KEY2").child("email").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("users").child(userId).child("email").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<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);
}
什么 updateChildren
方法做。是setValue ()
调用给定 Map<String, Object>
中的每一行作为节点的完整引用的键和值的对象。
更多更新删除数据可以在官方Firebase documentation阅读
关于android - 在 Firebase 中更新和删除数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41869606/