Juwdohr
Juwdohr

Reputation: 11

How can I get a random object from a Firebase Database?

I am trying to get a quote and author from a Firebase Database. Currently the database is set up like:

    [{
      "quotes": [{
        "quote":"Some quote.",
        "author": "Some author."
      },{
        "quote":"Some quote.",
        "author": "Some author."
      }]
    }]

What I want is a random quote and author, and store them in their own variable to be displayed in a TextView. Thank you all for your help, even if you just point me in the right direction.

Upvotes: 1

Views: 1971

Answers (1)

Victor Maldonado
Victor Maldonado

Reputation: 121

Unfortunately in Firebase is not possible to get random values from a list. However, you can get the size of the list and use the Random class for generating an int between 0 and the size of your list, and using it like an index, then you iterate in your list until the index randomly generated.

This is an example of how you can do it:

The content of Quote.class:

class Quote {
    String quote;
    String author;
}

The method for getting a random quote:

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("quotes");
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot != null) {
                Random random = new Random();
                int index = random.nextInt((int) dataSnapshot.getChildrenCount());
                int count = 0;
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    if (count == index) {
                        Quote quote = snapshot.getValue(Quote.class);
                        doSomethingWithYourQuote(quote);
                        return;
                    }
                    count++;
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Upvotes: 2

Related Questions