Ad

How Do I Access An Unknown Node In Firebase While Retrieving Data?

I want to retrieve the data beneath a node in Firebase which has an unknown ID. I have used push().getKey(), which assigns an unknown ID to each entry.

The structure of database is somewhat like this: Known ID->{Unknown ID 1: data1, Unknown ID 2: data2, Unknown ID 3: data3}

What do I use to access the data, in such way: ref.child(Known ID).child(Unknown ID)--> data but keeping in mind the random Unknown ID?

Referred other answers, but couldn't conclude. Tried, but retrieved a Null.

Ad

Answer

TLDR: If you don't know the ID/name of the child node, you can't fetch it directly.

Now, as far as I can understand from your explanation, your structure is something like this:

Root>User>More data added with unknown IDs.

I suggest you restructure it like this.

Root>User>Another child node with name say "userData">Add more data here with the unique IDs

userID1234:{
    ....,
    records:{
        record1:{},
        record2:{},
        so on
    }
}

This will help you fetch you data in one go by adding listener on the userData child.

Now do this to fetch all the records:

//Single event listener
databaseReference.child(userID).child("records").addListenerForSingleValueEvent(
    new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // Get all records
            if (dataSnapshot.exists()){
                // Use the fetched data which contains all the records
            }
        }
    });
Ad
source: stackoverflow.com
Ad