Mitchell Yuen
Mitchell Yuen

Reputation: 335

How to iterate through children in Firebase - Java

I want to iterate through children in a Firebase real time-database node

this is my Database Structure.

enter image description here

this is my Code.

  DatabaseReference RedLineRouteReference = FirebaseDatabase.getInstance().getReference().child("RedLineRoute");
                                    RedLineRouteReference.addValueEventListener(new ValueEventListener() {
                                        @Override
                                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                            Iterator i = dataSnapshot.getChildren().iterator();
                                            if(true)                                            {
                                                Toast.makeText(TimeTable.this, i.next().toString(), Toast.LENGTH_SHORT).show();

                                            }

                                        }

                                        @Override
                                        public void onCancelled(@NonNull DatabaseError databaseError) {

                                        }
                                    });

This program outputs

I/TimeTable: DataSnapshot { key = aMaison, value = true }

However i would like to isolate each iteration(each child)

for instance I would like to define the second child and the Third Child and so on...

Upvotes: 0

Views: 1514

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317392

The way you deal with an Iterable in Java is with a simple for loop:

for (DataSnapshot child: dataSnapshot.getChildren()) {
    String key = child.getKey();
    String value = child.getValue().toString();
    // do what you want with key and value
}

Upvotes: 1

Related Questions