Home > Software engineering >  How can we fetch the Firebase realtime database to List
How can we fetch the Firebase realtime database to List

Time:04-07

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()
            }
        })

Realtime Database Users Sample

CodePudding user response:

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()
    }
})
  • Related