Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase datasnapshot.getValue() returns null

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.Database 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.Debugged Answer

like image 512
Simon Avatar asked Nov 08 '22 17:11

Simon


1 Answers

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.

like image 86
harshithdwivedi Avatar answered Nov 15 '22 08:11

harshithdwivedi