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
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.
0
.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!