0
votes

I have two collections in my firestore database, the first is list of all the documents (BlockList), and the second for the users. when the user bookmark post on Recyclerview on the app, send the id of the document and timestamp to sub-collection (Favorites) under Users Collection.

i retrieve the list of documents based on this ids from the main collection (BlockList), but i want to arrange them according to timestamp for each user, so i've tried to order them by timestamp before adding them to Arraylist and Log the list, i've got the correct result. but the recyclerview still retrieved them ascending order by document ID !

firebaseFirestore.collection("Users")
                .document(userId).collection("Favorites").orderBy("timestamp", Query.Direction.DESCENDING).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    List<String> list = new ArrayList<>();
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        list.add(document.getId());
                    }
                    Log.d(TAG, list.toString());

                    if (list.size() != 0){
                        blockReffav = firebaseFirestore.collection("BlockList")
                                .whereIn(FieldPath.documentId(), list);

                        blockReffav.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                            @Override
                            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                                if(task.isSuccessful()){
                                    onFirestoreTaskComplete.blockListDataAdded(task.getResult().toObjects(BlockListModel.class));
                                } else {
                                    onFirestoreTaskComplete.onError(task.getException());
                                }
                            }
                        });

                    }

                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

BlockList Collection

sub-collection (Favorites) under Users Collection

1

1 Answers

0
votes

Given how you currently retrieve the documents:

blockReffav = firebaseFirestore.collection("BlockList")
        .whereIn(FieldPath.documentId(), list);

There is no way to specify the order of the IDs in the list in this query, so you will get them back in (the default) order of document IDs.

I see two options:

  1. Request the documents one by one, so that you get them in the correct order.
  2. Re-order the documents in your application code to match the order in the list.

I'd recommend the latter, as it's likely to be both simpler and more reliable.