Alex Zhang
Alex Zhang

Reputation: 63

How to add Map values in Firebase Realtime Database

I'm creating an app and trying to use Firebase Realtime Database to store the scores for my game. My database has many users, each of which contains a TreeMap with the date as the key and the score as the value. I am trying to have the player click a button and save their score inside the TreeMap. I am having trouble with reading the data in the TreeMap because I want this to be a one time read and not a listener.

I have tried retrieving the map first, updating it, and reuploading it to the database. However, I don't know how to link this to the button click, as online tutorials all seem to use a listener and snapshot.

private void showData(DataSnapshot dataSnapshot){
        String name = "";
        String age = "";
        String number = "";
        TreeMap<String, Integer> scores = new TreeMap<>();

        for (DataSnapshot ds: dataSnapshot.getChildren()){
            User user = new User();
            if (ds.child(userID).getValue(User.class).getScores() != null){
                ds.child(userID).getValue(User.class).getScores().put(date, totalScore);
                scores = ds.child(userID).getValue(User.class).getScores();
            }
            name = ds.child(userID).getValue(User.class).getUserName();
            age = ds.child(userID).getValue(User.class).getUserAge();
            number = ds.child(userID).getValue(User.class).getUserPhoneNumber();

        }

        scores.put(date, totalScore);
        User temp = new User(userID, name, age, number, scores);
        myRef.child(userID).setValue(temp);
    }

This is the solution I had written, but it doesn't incorporate the button click.

Upvotes: 1

Views: 1687

Answers (1)

Hasnain Sabir
Hasnain Sabir

Reputation: 200

 query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.getValue() != null) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    User user = snapShot.getValue(User.class);
                    if(user.getScores()!=null){
                        HashMap<String, Object> hashMap = new HashMap<>();
                           hashMap.put("date", date);
                           hashMap.put("totalScore", totalScore);
                           query.child(userId).setValue(hashMap);
                    }
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

this is how you update the score , you didnt show ur database schema so i i am not clearly give you the exact query.

Upvotes: 2

Related Questions