Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Firebase update existing value instead of setValue creating a new record [duplicate]

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.

like image 244
Carl Bruiners Avatar asked Oct 16 '25 11:10

Carl Bruiners


1 Answers

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.

like image 165
Peter Haddad Avatar answered Oct 19 '25 02:10

Peter Haddad