在单个RecyclerView中使用Firestore和Firebase RTDB中的数据 [英] Using data from Firestore and Firebase RTDB in single RecyclerView

查看:90
本文介绍了在单个RecyclerView中使用Firestore和Firebase RTDB中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个RecyclerView,该视图由存储在Firestore数据库中的帖子填充. 每个帖子都被写为具有唯一postID的文档,其中存储了发布的消息,时间戳和一个类似计数器.

I have a RecyclerView which is populated by posts stored in a Firestore database. Each post is written as a document with a unique postID, storing the posted message, a timestamp and a like-counter.

    //mUploads is defined as private List<Upload> mUploads;
    //Upload object stores post message, timestamp and likes      
    mUploads = new ArrayList<>();

    mFireStoreOrdered = mFireStoreInst.collection("posts").orderBy("time");
    mFireStoreOrdered
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (DocumentSnapshot doc : task.getResult()) {

                            //For each document get the ID
                            String postID = doc.getId();

                            // Upload object stores post message, timestamp and likes
                            Upload upload = doc.toObject(Upload.class).withId(postID);

                            mUploads.add(upload);
                        }

                        Collections.reverse(mUploads);

                        //Populate Recyclerview
                        mAdapter = new UploadAdapter(MainActivity.this, mUploads);

                        mContentView.setAdapter(mAdapter);


                    } else {
                        //...
                    }
                }
            });

在尝试为这些帖子实现赞"功能时,我陷入了Firestore的极限,Firestore每秒只能处理一次文档更新.

When trying to implement the "like"-functionality for these posts I got to the limits of Firestore, which can only handle one document update per second.

阅读本文让我确信使用Firebase实时数据库通过事务操作来存储喜欢的东西,而不是使用分布式计数器.我不想实时显示喜欢,我只想使用RTDB每秒处理多个喜欢/不喜欢.

Reading this article convinced me of using the Firebase Realtime Database to store the likes by using transaction operations instead of using distributed counters. I do not want to display the likes in real-time, I only want to use the RTDB to handle multiple likes/dislikes per second.

当另外使用Firebase RTDB进行点赞时,我会将数据添加到/posts/postID/likes路径.

When additionally using the Firebase RTDB for likes, I would add data to a path /posts/postID/likes.

在将其传递到适配器之前,如何从Firestore中获取发布消息,并将RTDB中的相应点赞添加到mUploads中.具体来说,是否可以确保在不查询每个postID的情况下,为其对应的帖子设置正确的like值.

How can I get the post messages from Firestore and add the corresponding likes from the RTDB to mUploads before passing it to the adapter. Specificially, is it possible to ensure that I set the correct like value to its corresponding post, without querying for each postID.

推荐答案

在Firestore中,这是一种非常常见的做法,用于将喜欢的次数存储在Firebase Realtime数据库中,否则,每次读取将向您收费/write操作,如我在此帖子中的回答所述.因此,使用Firebase Realtime数据库,您可以免费托管喜欢的人数.

This is a very common practice when it comes to Firestore, to store the number of likes in the Firebase Realtime database, otherwise you'll be charged for every read/write operation as explained in my answer from this post. So using Firebase Realtime database you can host the number of likes at no cost.

那么,该怎么办呢?首先,你猜对了.喜欢的次数应添加到postId下方,如下所示:

So, how can be done? First of all, you are guessing right. The number of likes should be added beneath the postId like this:

Firebase-root
   |
   --- likes
         |
         --- postIdOne: numberOfLikes //must be stored as an integer
         |
         --- postIdOTwo: numberOfLikes //must be stored as an integer
         |
         --- //and so on

要实现所需的功能,您需要执行以下步骤.

To achive what you want, you need to follow the next steps.

  1. 每次添加新帖子时,通过将特定帖子ID的值设置为0,在上述的Firebase Realtime数据库中添加相应的帖子ID.
  2. 每次您获得新的赞时,都会将该postId的值增加一.每当用户撤回一个赞时,将该postId的值减小一.为实现此目的并获得一致的数据,建议您使用 Firebase交易.
  3. 然后在您的适配器类中,当您想要为视图设置喜欢的数量时,您将在其中显示来自Firestore的数据,只需在该特定的post id节点上附加一个侦听器,即可获得喜欢的数量.在onDataChange()内部,将该数字设置为TextView,如下所示:

  1. Every time you you add a new post, add the corresponding post id in Firebase Realtime database like above by setting the value of that particular post id to 0.
  2. Every time you get a new like increase the value of that postId by one. Every time a user retracts a like, decrease the value of that postId by one. To achieve this and also to have consistent data, I recommend you use Firebase Transactions.
  3. Then in your adapter class, where you are displaying data from Firestore, when you want to set the number of likes to a view, just attach a listener on that particular post id node and get the number of likes. Inside the onDataChange() set that number to a TextView like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference noOfLikesRef = rootRef.child("likes").child(postId);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String numberOfLikes = "(" + dataSnapshot.getValue() + ")";
        numberOfLikesTextView.setText(numberOfLikes);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
noOfLikesRef.addListenerForSingleValueEvent(valueEventListener);

就是这样!

这篇关于在单个RecyclerView中使用Firestore和Firebase RTDB中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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