willy
willy

Reputation: 101

How do I retrieve data from multiple nodes in Firebase? Android

I'm trying to retrieve the questions from the questions node from each user as shown in the diagram below. I can't figure out a way to reach the nodes. How do I retrieve the data from each of the question nodes of the separate users?? someone please help. enter image description here

Upvotes: 0

Views: 171

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599956

To access the questions of all users you'd do something like this:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
            DataSnapshot questionsSnapshot = userSnapshot.child("questions");
            Log.i(TAG, "User "+userSnapshot.getKey()+" has "+questionsSnapshot.numChildren()+" questions");
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
}

I highly recommend reading the Firebase documentation on structuring data as you are nesting data of different types here, which goes against the recommendation to avoid nesting data.

Upvotes: 1

Related Questions