mechaadi
mechaadi

Reputation: 958

Firebase data retrieve with random keys

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.

data structure

Upvotes: 0

Views: 762

Answers (3)

Alex Mamo
Alex Mamo

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

Mohammad Sommakia
Mohammad Sommakia

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

Yunus Kulyyev
Yunus Kulyyev

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

Related Questions