1

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(){}
});
Carsten Hagemann
  • 957
  • 10
  • 23
  • See http://stackoverflow.com/q/40765613 or http://stackoverflow.com/q/40853157 or http://stackoverflow.com/q/42186839 – Frank van Puffelen Mar 26 '17 at 22:02
  • @FrankvanPuffelen Thanks, I believe only the third link is actually what I was asking about (first and second questions are not what this is), and in that solution it first creates a List and then adds everything to it, just to get one thing back. – Carsten Hagemann Mar 26 '17 at 22:09

1 Answers1

1

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) {

    }
});
Carsten Hagemann
  • 957
  • 10
  • 23