Ad

How To Make A RecyclerView Only With Documents That Have In Their Array A Number Larger Than X

My database is as follows:

enter image description here

If I would use a RecyclerView, how could I retrieve only the documents which has inside the schedules array the number 1908150000 (for example)?

One thing I know is that I can see the documents with the condition above using this code:

FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference eventRef = db.collection("Events");
eventRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        for (DocumentSnapshot documentSnapshot : task.getResult()) {
            List<Long> list = (List<Long>) documentSnapshot.get("schedules");
            for (Long listItem : list) {
                if (listItem > 1908100000) {
                    Log.d("TAG", documentSnapshot.getId());
                    break;
                 }
             }
         }
    }
});

And also, using a query, I know there is the function whereArrayContains() but it requires a fixed number to compare as in my case I need to make it a range.

So, is it possible to get the documents with this condition into a RecyclerView?

Ad

Answer

One thing I know is that I can see the documents with the condition above using this code.

This is not the best approach since you are getting all the documents in your Events collection and you do the filtering client side. I say so because everything in Firestore is about the number of reads and writes you perform. For small data sets it will solve your problem with not so much cost.

And also, using a query, I know there is the function whereArrayContains() but it requires a fixed number to compare as in my case I need to make it a range.

Using this database schema, no, you cannot query the database and in the same time filter on a range. Unfortunately Firestore doesn't currently have such a query that can help you do that. You can filter elements on range using whereLessThanOrEqualTo() and whereGreaterThanOrEqualTo() methods but it will work only a single property not on values that exist within an array.

That being said, I encourage you to send this as a request to the Firebase team.

Ad
source: stackoverflow.com
Ad