Here is the code I've tried. It only displays posts of the current user Here is the image of the firebase database to describe what I am trying to do:
I don't mind if the answer comes in java code too. I appreciate your assistance.
private fun retrievePosts() {
progressBar!!.visibility = View.VISIBLE
val postsRef = FirebaseDatabase.getInstance().reference.child("Catalog").child(uid!!)
postsRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
(postList as ArrayList<ModelPost>).clear()
for (snapshot in p0.children) {
val post = snapshot.getValue(ModelPost::class.java)
for (id in (followingList as ArrayList<String>)) {
if (post!!.getUid() == id) {
(postList as ArrayList<ModelPost>).add(post!!)
progressBar!!.visibility = View.GONE
}
adapterPost!!.notifyDataSetChanged()
}
}
}
override fun onCancelled(p0: DatabaseError) {
progressBar!!.visibility = View.GONE
}
})
}
CodePudding user response:
You're only reading the posts of the current user from the database with this: val postsRef = FirebaseDatabase.getInstance().reference.child("Catalog").child(uid!!)
.
To read the posts from all users, you should initialize val postsRef = FirebaseDatabase.getInstance().reference.child("Catalog")
, and then add an extra loop (across the user nodes) in your onDataChange
.
So something like:
val postsRef = FirebaseDatabase.getInstance().reference.child("Catalog")
postsRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
(postList as ArrayList<ModelPost>).clear()
for (userSnapshot in p0.children) {
for (snapshot in userSnapshot.children) {
val post = snapshot.getValue(ModelPost::class.java)
...