'How to put data from firebase to variable android? [duplicate]

fun getUnReadMessages(roomId: Int, userId: Int): Int {

    var counter: Int = 0
        database.getReference("/Conversations/").child(roomId.toString()).child("messages")
            .addValueEventListener(object : ValueEventListener {
                override fun onDataChange(snapshot: DataSnapshot) {
                    for (i in 0 until snapshot.childrenCount) {
                        val isRead =
                            snapshot.child(i.toString()).child("is_read")
                                .getValue(Boolean::class.java)

                        val senderId =
                            snapshot.child(i.toString()).child("senderid")
                                .getValue(Int::class.java)

                        if (senderId != userId && isRead == false) {
                            counter++
                        }
                    }
                    Log.i(TAG, counter.toString())
                }

                override fun onCancelled(error: DatabaseError) {
                    TODO("Not yet implemented")
                }

            })

    return counter
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source