如何使用 Cloud Firestore 查询用户的待定好友请求?

How can I query an user's pending friend requests using Cloud Firestore?

我目前无法尝试使用 FirestoreRecyclerAdapter 在 RecyclerView 中显示用户的待定好友请求。

这是我的数据结构:

  1. Users collection, which stores details about the user (name, profile image, status)
  2. Requests collection, in which I store two array lists of user ID's, one for pending requests and another for received requests

我想查询这样的东西,获取在数组中找到 userId 的所有用户文档。

    CollectionReference usersRef = db.collection("users");
    Query query = usersRef.whereIn("userId", requestsArray);
    FirestoreRecyclerOptions<User> options = new FirestoreRecyclerOptions.Builder<User>()
            .setQuery(query, User.class)
            .build();

这就是我从数据库中获取用户 ID 数组的方式

 currentUser = firebaseAuth.getInstance().getCurrentUser();
    DocumentReference requestsRef = db.collection("friend requests").document(currentUser.getUid());
    requestsRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if(task.isSuccessful()){
                DocumentSnapshot documentSnapshot = task.getResult();
                Requests request = documentSnapshot.toObject(Requests.class);
                requestsArray = request.getReceivedRequests();
            }
        }
    });

我正在努力解决的问题是在尝试查询 Users 集合和填充 RecyclerView 之前弄清楚如何确保 requests.get() 已完成并且数组不为空,因为我收到以下错误“java.lang.IllegalArgumentException:无效查询。'in' 过滤器需要非空数组。”。

我不得不提的是,我对 Firebase 还很陌生,还在学习它的工作原理。非常感谢任何 suggestions/help!

What I'm struggling with is figuring out how to make sure that requests.get() has finished

当“onComplete()”方法触发时,您将始终 100% 确定“requestsRef.get()”已完成从数据库加载数据。这意味着可以读取“requestsRef”位置的所有数据,没有安全规则拒绝读取操作,现在所有数据都可用于任何其他操作。因此,您总是需要等待数据可用,以便在另一个查询中使用,例如。

and the array is not null before trying to query the Users collection and populating the RecyclerView

为了解决这个问题,您可以考虑实例化存在于“请求”class 中的两个数组“receivedRequests”和“sentRequests”。这样,当数组中没有 ID 时,您将得到一个空数组和 not“null”。如果您不想这样做,您还可以检查无效性。

但是,出现如下错误:

java.lang.IllegalArgumentException: Invalid Query. A non-empty array is required for 'in' filters.

发生是因为当您将“requestsArray”对象发送到“whereIn()”方法时,数据尚未从数据库加载完成。因此,任何需要来自 Firestore 的数据的代码都需要在“onComplete()”方法中,或者从那里调用。因此,在这种情况下最简单的解决方案是移动以下代码行:

CollectionReference usersRef = db.collection("users");
Query query = usersRef.whereIn("userId", requestsArray);
FirestoreRecyclerOptions<User> options = new FirestoreRecyclerOptions.Builder<User>()
        .setQuery(query, User.class)
        .build()

在“onComplete()”方法内部,在以下代码行之后:

requestsArray = request.getReceivedRequests();

通过这种方式,您将确保您永远不会确定空数组。在最坏的情况下,您将使用空数组而不是未使用的数组。