-1

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Joan P.
  • 2,368
  • 6
  • 30
  • 63
  • For retrieve such data either you need them to be sorted by date or any other fields. Like i have tried in my [Question](https://stackoverflow.com/questions/56543580/problem-with-implementing-pagination-data-load-before-reach-at-last-card). – Ashish Aug 22 '19 at 09:13
  • Please post your database screenshot or layout. – Ashish Aug 22 '19 at 09:13
  • @Ashish Why should it be ordered when I need them random? I don't see how that answer can help me. I have a collection of items. Each item is a document with two details, id and name. Thanks anyway. – Joan P. Aug 22 '19 at 09:16
  • @loana If you entered in Firebase Firestore console. Please check inside Collection you can sort them by using fields only. So it will help you retrieve data properly. – Ashish Aug 22 '19 at 09:19
  • @Ashish I'm really confused now. Why should I check the console? I need to get those random items in code. I use FirestoreRecyclerAdapter from FirebaseUi. – Joan P. Aug 22 '19 at 09:21
  • Even they have properly defined in their [docs](https://firebase.google.com/docs/firestore/query-data/query-cursors). Even `startAfter()` takes only document field not id. – Ashish Aug 22 '19 at 09:21
  • Possible duplicate of [Firebase: Pull random data from Firebase to RecyclerView (android)](https://stackoverflow.com/questions/42042219/firebase-pull-random-data-from-firebase-to-recyclerview-android) – Jake Lee Aug 22 '19 at 09:55
  • @JakeSteam I think that you also didn't understand me. I'm using FirestoreRecyclerAdapter, so I don't find a solution for that. Do you have any other approach? – Joan P. Aug 22 '19 at 10:31

1 Answers1

1

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807