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

六眼飞鱼酱① 提交于 2020-06-17 02:45:06

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/49101324/android-firebase-update-existing-value-instead-of-setvalue-creating-a-new-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!