Search code examples
androidfirebasekotlingoogle-cloud-firestorefirebaseui

How to display only 15 random items from collection Cloud Firestore in Kotlin?


I have a collection of over 1000 items. I cannot display all of them due to the high cost. What I want is to display only 15 in a RecyclerView but every time random. I'm using FirestoreRecyclerAdapter and I cannot find any way to do that. Is this possible? If yes, how? Any help would be appreciated.


Solution

  • There is nothing built into the FirebaseUI FirestoreRecyclerAdapter for showing a random selection of items.

    The closest I can think of is to:

    1. add a random integer to each document when you create it
    2. generate a random integer when you need to display the recycler view
    3. display the documents closest to the random value in the recycler view with a query. Something like citiesRef.whereGreaterThan("randomField", randomValue).limit(15)

    This is based on Dan's answer here: Firestore: How to get random documents in a collection, by combining his "Random Integer version" and "Keep it coming" sections.

    If you don't like this approach, you'll have to build your own adapter. You'll still need some of the approaches from Dan's linked answer in that case to select a random document.