Java Firestore Android 在查询中使用数组列表来显示来自关注用户的帖子 [英] Java Firestore Android use an arraylist in a query to show posts from followed users

查看:25
本文介绍了Java Firestore Android 在查询中使用数组列表来显示来自关注用户的帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个显示用户关注的用户帖子的活动.对于帖子,我使用了以下结构:

I am developing an activity that displays the posts of the users that the user follows. For the posts I used the following structure:

  root --- posts (collection)
             |
             --- uid (documents)
                  |
                  --- userPosts (collection)
                        |
                        --- postId (documents)
                        |     |
                        |     --- title: "Post Title"
                        |     |
                        |     --- date: 4/06/2021
                        |
                        --- postId (documents)
                              |
                              --- title: "Post Title"
                              |
                              --- date: 08/06/2021
                              |
                              --- description: "this is the description of the post"
                              [...etc]

最近我做了一个可视化用户帖子的活动,就是这样.现在,相反,我想显示用户在主页中关注的用户的帖子.这是以下"的结构:帖子(收藏)

Lately I did an activity that visualized the posts of a user and that's it. Now, instead, I want to show the posts of the users that the user follows in the home page. This is the structure of the "following": posts (collection)

   root--- folowing(documents)
              |
              --- uid(collection)
                    |
                    --- userFollowing(documents)
                          |
                          --- followed user(collection) -- followed user(document)
                          |
                          --- followed user (collection) -- followed user(document)

因此,我尝试收集 Arraylist 用户以这种方式跟随的所有用户 uid:

So, I tried to collect on an Arraylist all user uids that are followed by the user in this way:

FirebaseFirestore.getInstance().collection("following").document(FirebaseAuth.getInstance().getCurrentUser().getUid()).collection("userFollowing").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    document.getData();
                    Uidrecord.add(cont,String.valueOf(document.getData()));
                    cont++;
                }
                int conta = 0;
                for (String item: Uidrecord){
                    if(item == null)
                        break;
                    uidFollowing.add(conta,getFollowingUid(item));
                    Toast.makeText(MainActivity.this, uidFollowing.get(conta), Toast.LENGTH_SHORT).show();
                    conta++;

                }
            } else {
                Toast.makeText(MainActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
            }
        }
    });

(uid 下面是一个用户的所有id)这是我设置查询以获取单个用户的帖子数据的方式:

(uid Following contains all the ids of a user) This is how I set up the query to fetch a single user's post data:

Query query = FirebaseFirestore.getInstance()
                .collection("post/" + uidVisit + "/userPosts")
                .limit(1000);

我知道我必须在其中查找帖子的用户 ID,所以这是一个静态查询,因为我必须获取用户的帖子,仅此而已.现在,获取帖子的 uid 包含在一个数组列表中.所以我想知道如何创建动态查询,然后如何获取每个关注的用户的帖子(使用 RecyclerView).有可能吗?

I knew the user id I had to look for posts in, so it was a static query because I had to get a user's posts and that's it. Now instead the uid where to get the posts are contained in an arraylist. So I was wondering how I could create a dynamic query and then how to grab the posts of every single user followed (using RecyclerView). It's possible to do it?

编辑:正如您从我的完整代码中看到的 https://codeshare.io/MNWYb3 我尝试放置一个 for(第 225 行)并动态化查询,但结果是它只显示用户的帖子,仅此而已(似乎覆盖了适配器的每个帖子,实际上显示的帖子是最后一个人跟着所以最后一个数组列表项)

Edit: As you can see from my complete code https://codeshare.io/MNWYb3 I tried putting a for (line 225) and dynamizing the query, but the result is that it only shows the posts of a user and that's it (seems to override each for the adapter, in fact the post shown is the last person followed so the last arraylist item)

推荐答案

以你目前在 Firestore 上的结构这会有点困难,我认为你应该首先简化你的结构,我建议你保持这样的结构:

With your current structure on Firestore this is going to be a bit difficult, I think you should first simplify your structure, I would suggest you keep a structure like this:

users
|
--- uid : "uid1"
    name: "John Doe"
    ...
    usersFollowed : [uid1, uid2, ..., uidn]
    userPosts (collection)
    |
    --- uid: "uuid1"
        title: "Post Title"
        date: 08/06/2021
        description: "this is the description of the post"
        userId: "uid1"
        ....

有了这个,您只对单个集合及其子集合进行操作,这降低了一点复杂性,您将在每个用户的 usersFollowed 数组字段中存储每个用户关注的用户列表用户文档.

With this you are only operating on a single collection and a it's subcollection, which lowers complexity a bit, you would be storing the list of users that each user follows in the usersFollowed array field of each user document.

接下来你可以随机迭代usersFollowed的列表:

Up next you could iterate the list of usersFollowed randomly:

List<String> listOfFollowed = new ArrayList<>();
// userDocument is your current user
listOfFollowed = userDocument.get(usersFollowed);
Collections.shuffle(listOfFollowed);
List<DocumentSnaphot> listOfPosts = new ArrayList<DocumentSnaphot>();
for (String item : listOfFollowed) {
    Query query = FirebaseFirestore.getInstance()
                                   .collection("users")
                                   .document(userDocument.getId())
                                   .collection("userPosts")
                                   .document(item)
                                   .orderBy("date")
                                   .limit(1);
    listOfPosts.add(query.get().getDocument().get(0));
}

此代码将按随机顺序为您提供当前用户关注的每个用户的最新帖子.

This code is going to give you the single latest post of each user that is followed by the current user in a random order.

这不是动态查询,但它会为您提供随机结果,您可以调整最初希望从每个用户那里获得多少帖子背后的逻辑,或者创建一个触发并在以下时间获得更多帖子的函数用户已经看到了你已经获取的所有内容等等.

It's not a dinamic query, but it will be giving you random results, and you can tweek the logic behind how many post from each users you want to get at first, or create a function that is triggered and gets more post when the user has seen all the ones you already fetched and so on.

编辑

检查您的完整代码我得出的结论是您面临的问题与使用 FirestoreRecyclerAdapter 相关,它需要一个查询作为参数,但是,您的用例要求您在循环中一遍又一遍地执行您的查询以获取结果.将相同的查询作为 FirestoreRecyclerAdapter 的选项传递将导致您得到一个查询,该查询仅获取列表中的最后一个 userFollowed,因为这将是它在循环,并将在应用程序的执行中向前移动,这不是预期的结果.

Checking your complete code I came to the conclusion that the issue you are facing is related to the use of a FirestoreRecyclerAdapter, which expects a query as a parameter, however, your use case requires you to execute your query over and over again in a loop to get the results. Passing that same query as an option for the FirestoreRecyclerAdapter will result on you getting a query that only get the last userFollowed in your list, as this will be it's final iteration in the loop and will be what is moved forward in the app's execution, which is not the expected result.

因此,不要使用 FirestoreRecyclerAdapter,我建议您使用 ListAdapter,它需要一个 List 作为参数.您将用作此参数的列表将是一个新列表,其中填充了在您创建的循环中反复执行的查询结果.

So instead of using a FirestoreRecyclerAdapter I would recommend you to use a ListAdapter, which expects a List as a parameter. The list you will use as this parameter will be a new list that is populated with the results of your query being executed over and over in that loop you created.

话虽如此,我建议您查看该文档,看看这可能意味着您的代码中还有哪些其他更改,因为您将更改正在使用的类的类型,这可能会产生意想不到的后果.另外本教程可能会有所帮助.

That being said, I would recommend you to take a look at that documentation and see what other changes this might imply in your code since you will be changing the type of class you are using and this might have unexpected consequences. Also this tutorial might help.

这篇关于Java Firestore Android 在查询中使用数组列表来显示来自关注用户的帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆