如何更新Firebase中的项目?

时间:2017-04-10 17:59:41

标签: android firebase firebase-realtime-database

这是我要更新的数据:

"users": [
    "-KTYWvZG4Qn9ZYTc47O6": {
        "name": "name"
        "email": "email"
    }
]

我的代码:

private void update1(String s, String name,String email) {

    String key = mFirebaseDatabase.child("users").push().getKey();

    user1 user = new users1(name, email);
    Map<String, Object> postValues = user.toMap();

    Map<String, Object> childUpdates = new HashMap<>();
    childUpdates.put("/users/" + key, postValues);

    mFirebaseDatabase.updateChildren(childUpdates);
}

为什么要创建新节点?

"users": [
    "-KTYWvZG4Qn9ZYTc47O6" : {
        "name" : "name"
        "email" : "email"
   }
]
"users": [
    "-KeZvOQ8HYrNXvuPBe8z" : {
        "name" : "name2"
        "email" : "email2"
    }
]

2 个答案:

答案 0 :(得分:1)

您需要在示例中按照电子邮件等唯一值查询节点 使用此代码 youReference = database.getReference(“masjeds”);

ValueEventListener listener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { 
                masjedKey = dataSnapshot1.getKey(); // This is a member variable
                masjed = dataSnapshot1.getValue(Masjed.class); // This is a member variable
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
};
masjeds.orderByChild("id").equalTo(masjed.getId()).addValueEventListener(listener);

然后使用

获取密钥
datasnapshot.getkey () 

使用

更新它
youReference.child(masjedKey).child("name").setValue("John")

答案 1 :(得分:0)

您正在使用push(&#34;创建对自动生成的子位置的引用&#34;)方法创建新节点:

mFirebaseDatabase.child("users").push().getKey();

只需删除它,这将更新现有的users节点:

mFirebaseDatabase.child("users").getKey();