'How can we fetch the Firebase realtime database to List
Here I am Trying to Display "users" into Recycleview and I need to Get Data Into List
databaseReference?.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val list = dataSnapshot.child("users")
for (e in dataSnapshot.children) {
Log.i("messageData", e.toString())
}
Log.i("messageData", userList.toString())
}
override fun onCancelled(databaseError: DatabaseError) {
Toast.makeText(
this@MessageActivity, "database error",
Toast.LENGTH_SHORT
).show()
}
})
Solution 1:[1]
Here, I got my solutions
private val userList: ArrayList<UserList> = ArrayList()
databaseReference?.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (data in dataSnapshot.children) {
val model = data.getValue(UserList::class.java)
if (personalEmail != model?.email)
userList.addAll(listOf(model as UserList))
}
}
#UserList class
data class UserList(
val email: String? = null,
val full_name: String? = null,
val phoneNumber: String? = null,
val profile_image: String? = null
)
Solution 2:[2]
You can get the list like the below example:
databaseReference?.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val userList = dataSnapshot.children.map { snap -> User(
snap.child("Name").getValue(String::class.java)?:"",
snap.child("email").getValue(String::class.java)?:"",
snap.child("phone").getValue(Long::class.java)?:0,
) }
}
override fun onCancelled(databaseError: DatabaseError) {
Toast.makeText(
this@MessageActivity, "database error",
Toast.LENGTH_SHORT
).show()
}
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aashis |
| Solution 2 | Alex Mamo |
