Carsten Hagemann
Carsten Hagemann

Reputation: 1144

How does one get a random children of a Firebase node?

First off, here's my Database structure:

firebase database structure

My goal was to get a random Question object from the "DE" node to later display it, and as there's no builtin support for querying a random child I have to get a random Object myself, from that iterator, somehow.

Currently, I have this code, but am confused on how to string it together:

    DatabaseReference questionsRef = FirebaseDatabase.getInstance().getReference().child("questions").child("DE");

questionsRef.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int questionCount = (int) dataSnapshot.getChildrenCount();
        int rand = random.nextInt(questionCount);
        Iterator itr = dataSnapshot.getChildren().iterator();
    }
    // onCancelled(){}
});

Upvotes: 1

Views: 2729

Answers (1)

Carsten Hagemann
Carsten Hagemann

Reputation: 1144

Basically, you just have to do enough itr.next() until the iterator is at the nth position (where n is the random number from nextInt()) and then you can simply get the Object you want with getValue(), the example below should show it well:

questionsRef = FirebaseDatabase.getInstance().getReference().child("questions").child("DE");

questionsRef.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int questionCount = (int) dataSnapshot.getChildrenCount();
        int rand = random.nextInt(questionCount);
        Iterator itr = dataSnapshot.getChildren().iterator();

        for(int i = 0; i < rand; i++) {
            itr.next();
        }
        childSnapshot = (DataSnapshot) itr.next();
        question = childSnapshot.getValue(Question.class);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

Upvotes: 1

Related Questions