How to exclude an element from a Firestore query?

后端 未结 7 1169
心在旅途
心在旅途 2020-12-01 22:12

I have a collection of users and I want to query all users from the database and display them in a RecyclerView except one, mine. This is my db

相关标签:
7条回答
  • 2020-12-01 22:46

    Simpler and earlier client-side filtering (when you add items to your list):

    1. Get the current user's ID by using Firestore's standard method.
    2. Get the name of the doc for all the users in your user collection.
    3. Before adding the user to your RecyclerView list, check that the user it is about to add to your list is not the current user.

    When done is this way, you can use the "not equals" method on the client side and not get into any Firestore issues. Another benefit is that you don't have to mess with your adapter or hide the view from a list-item you didn't want in the recycler.

    public void getUsers(final ArrayList<Users> usersArrayList, final Adapter adapter) {
    
        CollectionReference usersCollectionRef = db.collection("users");
    
        Query query = usersCollectionRef
                .whereEqualTo("is_onboarded", true);
    
        query.get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
    
                                final String otherUserID = document.getId();
    
                                 FirebaseUser user = mAuth.getCurrentUser();
                                 String currentUserID = user.getUid();
    
                                if (!otherUserID.equals(currentUserId)) {
    
                                  usersArrayList.add(new User(otherUserID));
                                  adapter.notifyDataSetChanged(); //Ensures users are visible immediately
                                                }
                                            } else {
                                                Log.d(TAG, "get failed with ", task.getException());
                                            }
                                        }
                                    });
                                }
    
                            }
                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });
    }
    
    0 讨论(0)
提交回复
热议问题