jayanth
jayanth

Reputation: 63

How to get data of a child in Firebase

I have my database tree structure like this:

enter image description here

Please tell me how do I get the value of "username" if I have the value of "userid"

Upvotes: 0

Views: 56

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138804

how do I get the value of "username" if I have the value of "userid"

To solve this, please use the following lines of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String username = dataSnapshot.child("username").getValue(String.class);
        Log.d(TAG, username);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
uidRef.addListenerForSingleValueEvent(valueEventListener);

The output in the logcat will be:

hisoka

Upvotes: 1

Related Questions