Reputation: 431
I have the following tree structure
[
I need to get the information Name and Details alone and their children.
I have done this, but doesn't run and shuts down the application when executed:
info = FirebaseDatabase.getInstance().getReference();
info.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot infoSnapshot: dataSnapshot.getChildren()) {
Log.i(TAG, infoSnapshot.child(info.toString()).getValue(String.class));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.i(TAG, "onCancelled", databaseError.toException());
}
});
How to solve this?
Upvotes: 0
Views: 3247
Reputation: 138824
To get the data from the root node, please use the code below:
info = FirebaseDatabase.getInstance().getReference();
info.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String child = ds.getKey();
Log.d("TAG", child);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.i(TAG, "onCancelled", databaseError.toException());
}
});
The output will be:
details
name
Upvotes: 6
Reputation: 11
Once you get the data snapshot, then you can easily iterate through all the data received..
info = FirebaseDatabase.getInstance().getReference();
info.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot infoSnapshot:dataSnapshot.child("details").getChildren()) {
Log.i(TAG, infoSnapshot.getValue(String.class));
}
for(DataSnapshot infoSnapshot:dataSnapshot.child("name").getChildren()){
Log.i(TAG, infoSnapshot.getValue(String.class));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.i(TAG, "onCancelled", databaseError.toException());
}
});
Upvotes: 1
Reputation: 5329
Delete this line is useless :
mDatabase= FirebaseDatabase.getInstance().getReference();
and change this like
info = FirebaseDatabase.getInstance().getReference(mDatabase.toString());
to
info = FirebaseDatabase.getInstance().getReference();
also this:
Log.i(TAG, infoSnapshot.child("root").getValue(String.class));// the root node doesn't exists
Upvotes: 0