Meg Bobo
Meg Bobo

Reputation: 43

How do I retrieve a list of all children in a Firebase realtime database?

The structure of my Firebase database is shown below. I want to make a list of all the Rooms in Android Studio. In other words, I need an array of [Room1, Room2, ...] for use in a spinner. How can I do this?

enter image description here

Upvotes: 0

Views: 482

Answers (1)

PradyumanDixit
PradyumanDixit

Reputation: 2375

What you can do is loop over all the children of your database and add them to an ArrayList and then use an array adapter to display the list.

What I am saying, looks something like this in code:

rootRef.child("Rooms").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
       for (DataSnapshot ds : dataSnapshot.getChildren()) {
            array.add(ds.child("Users").child("UserID").getValue(String.class));
        }

        ArrayAdapter adapter = new ArrayAdapter(YourActivity.this, android.R.layout.simple_list_item_1, array);
        listView.setAdapter(adapter);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        // Do something for errors too
    }
});

Upvotes: 2

Related Questions