Using data from Firestore and Firebase RTDB in single RecyclerView

前端 未结 1 974
终归单人心
终归单人心 2021-01-26 07:45

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 timestam

相关标签:
1条回答
  • 2021-01-26 07:59

    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.

    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. 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);
      

    That's it!

    0 讨论(0)
提交回复
热议问题