Android Firebase更新现有值,而不是setValue来创建新记录 [英] Android Firebase update existing value instead of setValue creating a new record
问题描述
我的Android应用上有一个按钮,当按下该按钮时,它将更新Firebase数据库中的分数;
I have a button on my Android app that when pressed should update the score in the Firebase database;
// UPDATE DATABASE START
final String getArgument = getArguments().getString("matchid");
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
final DatabaseReference ref = database.child("Matches");
final Query gameQuery = ref.orderByChild("gameID").equalTo(getArgument);
gameQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if(snapshot.exists()){
for (DataSnapshot child: snapshot.getChildren()) {
ref.child(getArgument).child("homeScore").setValue(5);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//UPDATE DATABASE END
执行代码时,我在数据库中获得了一条新记录,而不是更新现有字段数据.我通过Firebase控制台手动启动了数据库,而不是通过编程方式更新记录,因此我使用在数据库中作为PK创建的gameID. 我已经将该值硬编码为要更新为5的值,以使其首先起作用.
When I execute the code I get a new record in the database instead of updating the existing fields data. I've hand cranked the database through the Firebase console instead of programmatically updating the records, so I use gameID that I created as my PK in the DB. I've hard coded the value to be updated to 5 to get it working first.
Firebase中的数据结构是;
The data structure in Firebase is;
-Matches
- Match_01
-matchID
-homeScore
-etc....
感谢所有帮助.
推荐答案
要更新,您需要执行以下操作:
To update, you need to do this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Matches").child("Match_01");
Map<String, Object> updates = new HashMap<String,Object>();
updates.put("matchID", newID);
updates.put("homeScore", newscore);
//etc
ref.updateChildren(updates);
更多信息在这里:
https://firebase.google.com/docs /database/android/read-and-write#update_specific_fields
要同时写入节点的特定子节点而不覆盖其他子节点,请使用updateChildren()方法.
To simultaneously write to specific children of a node without overwriting other child nodes, use the updateChildren() method.
这篇关于Android Firebase更新现有值,而不是setValue来创建新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!