Ad

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...

Ad

Answer

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
}
Ad
source: stackoverflow.com
Ad