3

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.

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
Carl Bruiners
  • 516
  • 1
  • 7
  • 21

1 Answers1

6

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.

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • What the difference `ref.updateChildren(updates);` from `ref.setValue(updates);`?. It seems both method do the same thing – user924 May 31 '19 at 23:23
  • `setValue` will do more than one call to the database while `updateChildren` will do one call. Also `setValue` will override what is written under the parent node – Peter Haddad Jun 01 '19 at 05:28