Reputation: 958
I have a firebase data structure for my android app and I want to retrieve the data from random keys generated by push() method which is child of Forum node which is a child of root of the database. Please suggest me a way to do this. Thanks.
Upvotes: 0
Views: 762
Reputation: 138824
To display the values of all the children under Forums
node, please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference forumsRef = db.child("Forums");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
String ques = ds.child("ques").getValue(String.class);
String title = ds.child("title").getValue(String.class);
String uid = ds.child("uid").getValue(String.class);
Log.d("TAG", name + " / " + ques + " / " + title + " / " + uid);
}
}
@Override
public void onCancelled(DatabaseError error) {
Log.d("TAG", error.getMessage()); //Never ignore potential errors!
}
};
forumsRef.addListenerForSingleValueEvent(valueEventListener);
Upvotes: 1
Reputation: 1833
first you should write your class model "FormusModel" to store the data from server you can use this
> >
rootRef.child("Forums").addChildEventListener(new
> ChildEventListener() {
> > @Override
> > public void onChildAdded(DataSnapshot dataSnapshot, String s) {
> > ForumsModel model = dataSnapshot.getValue(FormusModel.class);
//now you can use model.getname();....
> }
Note: you must implemnt another method like onChildCahnge listener
Upvotes: 1
Reputation: 1022
You can get all of the children nodes of the parent "Forum" node. Just use getChildren() method. Then just randomly select one of the child node at position index.
DataSnapshot snapshot = dataSnapshot.child("Forums");
Iterable<DataSnapshot> children = snapshot.getChildren();
for (DataSnapshot child: children) {
Object obj = child.getValue(Object.class);
}
Upvotes: 1