How to get child value of child from firebase in android?
To access the value in your database, you create a DatabaseReference
location for that. Here are three links to places in your database:
DatabaseReference zonesRef = FirebaseDatabase.getInstance().getReference("ZONES");
DatabaseReference zone1Ref = zonesRef.child("ZONE_1");
DatabaseReference zone1NameRef = zone1Ref.child("ZNAME");
In this snippet:
-
zonesRef
points to/ZONES
-
zone1Ref
points to/ZONES/ZONE_1
-
zone1NameRef
points to/ZONES/ZONE_1/ZNAME
See the Firebase documentation on getting a database link for more information.
You can attach a listener to each of the links to get the value at that location. For example, to get the value /ZONES/ZONE_1/ZNAME
:
zone1NameRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, dataSnapshot.getValue(String.class));
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
}
});
For more information on this type of read operation, see the Firebase Reading Values documentation .
If you listen instead /ZONES/ZONE_1
, you get the DataSnapshot
entire node with all its properties. Then you use DataSnapshot.child()
to get from it ZNAME
:
zone1Ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, dataSnapshot.child("ZNAME").getValue(String.class));
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
}
});
One level higher, you can listen /ZONES
, which will give you a snapshot of all areas. Since this handles multiple children, you need to iterate over them with DataSnapshot.getChildren()
:
zonesRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot zoneSnapshot: dataSnapshot.getChildren()) {
Log.i(TAG, zoneSnapshot.child("ZNAME").getValue(String.class));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
}
});
For more information, see the Firebase documentation on listening for lists of data .
Finally, you can query to find a specific zone, for example to find a zone with "ZCODE": "ECOR"
:
Query zonesQuery = zonesRef.orderByChild("ZCODE").equalTo("ECOR");
zonesQuery.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot zoneSnapshot: dataSnapshot.getChildren()) {
Log.i(TAG, zoneSnapshot.child("ZNAME").getValue(String.class));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
}
});
To learn more about this, read the Firebase documentation on Sorting and Filtering Data .
source to share