In my app, I have used Firebase database and stored userID in a child and set the value of the child as username to get the username of the current user. Now I'm using addValueEventListener to get the username from the database. This is my Firebase structure.
The code is given below.
checkUsername.child("check").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
currentUser = dataSnapshot.child(getUserID()).getValue(String.class);
Log.d(TAG, "onDataChange: currentUser = " + currentUser);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
While debugging, String currentUser
returns null.
Screenshot of debugged answer.
Since you have added the valueEventListener at the check
node, so getting the child again makes no sense (Because the User ID is the key of check
node and not a separate child).
Instead try calling dataSnapshot.getChildren();
directly to get the entire list of updated data and iterate through it to get whatever key value you need.
Something like this,
checkUsername.child("check").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
String current value = dataSnapshot.getValue(String.class);
Log.d("TAG", "onDataChange: " + current value);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
Another option in this particular use case is to add a ChildEventListener and get the value inside onChildAdded()
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With