Ad

How To Query A List Of Strings Instead Of A Single String And Get A List Of Results From Firestore

I have a list of IDs of favorite items of a user locally stored in a list of strings. Now when user opens his favorite section the app needs to fetch all the items in the local favorite list from Cloud Firestore. Now what I see is only query that accepts a field and only a string (in my case only a single id of favorite item at a time).

Is there a way to pass the list of IDs as a Query in a single operation and get the result. What I am doing now is passing the IDs to RecylerView adapter and fetching it one by one in the BindViewHolder.

@Override
public void onBindViewHolder(final ImageViewHolder holder, int position) {

    db.whereEqualTo("imageId",mUploads.get(position))
            .get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            List<Upload> uploadsList = queryDocumentSnapshots.toObjects(Upload.class);
            Upload uploadCurrent = uploadsList.get(0);

            holder.materialCardView.setCardBackgroundColor(Color.parseColor(uploadCurrent.getImageColor()));
            Glide.with(mContext)
                    .load(uploadCurrent.getImageUrl())
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .centerCrop()
                    .into(holder.imageView);

        }
    });

}
Ad

Answer

Is there a way to pass the list of IDs as a Query in a single operation and get the result.

No, there is not not. You cannot pass a list or an array of strings to your query and get the results in one go. When calling get() on a Query object, the object that is returned is of type Task. Iterate through your list, create those Task objects and add all of them to a List<Task<DocumentSnapshot>> and then pass that list to Tasks's whenAllSuccess() method as it is explained in my answer from the following post:

Edit:

You should iterate through your list of strings and create the Task objects.

Task<DocumentSnapshot> documentSnapshotTask = collRef.document(stringFromList).get();

So at every iteration add the Task object to a list of tasks:

List<Task<DocumentSnapshot>> tasks = new ArrayList<>();

At the end just pass tasks list to whenAllSuccess() method, that's it.

Ad
source: stackoverflow.com
Ad