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
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.
The data structure in Firebase is;
-Matches
- Match_01
-matchID
-homeScore
-etc....
All help appreciated.
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);
more info here:
https://firebase.google.com/docs/database/android/read-and-write#update_specific_fields
To simultaneously write to specific children of a node without overwriting other child nodes, use the updateChildren() method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With