java – How to store users score in Firebase with android studio and how to access the child node in firebase-ThrowExceptions

Exception or error:

I have been trying to make an app that would let users take an assessment and then reveal their score. The registration of users is already working however i am trying to add score node in that parent node. I cant access the child node and i cant update the users score. please help me.The User is the parent node and its child is Rona.

How to solve:

To solve this, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("Users").child("Rona");
Map<String, Object> map = new HashMap<>();
map.put("score", 0);
ref.updateChildren(map);

The result will be the addition of the score property in your database with the value of 0.

Edit: According to your comment:

but i wanted to access other users to. not just Rona

To solve this, you need to use a query that looks like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Users").orderByChild("username");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            Map<String, Object> map = (Map<String, Object>) ds.getValue();
            map.put("score", 0);
            ds.getRef().updateChildren(map);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage());
    }
};
query.addListenerForSingleValueEvent(valueEventListener);

Using the above code, you’ll be able to update the score property not only to Rona but to all the other users.

Leave a Reply

Your email address will not be published. Required fields are marked *