0
votes

my firebase

I'm trying to retrieve all child nodes "userID" from firebase and store them in userList array list. Datasnapshot object dsp pulls all the data but it can't pass it to userList which always empty. Here is my code snippet:

groupList = FirebaseDatabase.getInstance ().getReference ().child ( "Group Members" );

groupList.addValueEventListener(new ValueEventListener()
{

    @Override
    public void onDataChange( DataSnapshot dataSnapshot)
    {
        List<String> userList = new ArrayList<> ();

        for (DataSnapshot dsp : dataSnapshot.getChildren ())
        {

            String  uID = dsp.child ("userID").getValue().toString ();
            userList.add ( uID );
        }
    }

What do you suggest to change in the code?

1
Try to intialize the userlist outside the onValueEventListenerMuhammad Hanzilah

1 Answers

0
votes

You're only looping over the direct child nodes of Group Members, so your dsp variable points to Android11, mgrp and the lovers. Since none of those has a property userID, the uID variable will indeed always be null or empty.

You'll need to loop over the nested level in your JSON (the keys like MtNY...) to be able to get the userID values.

So:

groupList = FirebaseDatabase.getInstance().getReference("Group Members" );

groupList.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange( DataSnapshot dataSnapshot) {
        List<String> userList = new ArrayList<> ();

        for (DataSnapshot snapshot: dataSnapshot.getChildren ()) {
            for (DataSnapshot userSnapshot: snapshot.getChildren ()) {
                String  uID = userSnapshot.child ("userID").getValue(String.class);
                userList.add ( uID );
            }
        }
    }