0

I am using firebase real database and I need to retrieve some user data and return that data as hashMap in the function "searchNumberOfMessages(user: User)".

I tried doing like the following,but it returns null hashMap:

Global Declarations:

private var hashMapArray = ArrayList<HashMap<String, Any?>>()
var newMessages = MutableLiveData<List<HashMap<String, Any?>>>()

The Function:

fun searchNumberOfMessages(user: User): HashMap<String, Any?> {

    val hasMap = HashMap<String, Any?>()

    chatRef.addValueEventListener(object : ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot) {

            val messageArray = ArrayList<String?>()

            for (snapshot2 in snapshot.children) {

                val chat = snapshot2.getValue(Message::class.java)

                if (chat!!.receiver.equals(currentUser!!.uid) && chat.sender.equals(
                        user.uid
                    )
                ) {

                    if (chat.seen == false) {
                        messageArray.add(chat.message)
                    }

                }
            }

            hasMap["Sender"] = user
            hasMap["SenderUID"] = user.uid
            hasMap["Messages"] = messageArray.size
            hashMapArray.add(hasMap)
            newMessages.postValue(hashMapArray)

            Log.e("hasMap","hasMap: $hasMap")

        }

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

    })
    
    return hasMap

}

hasMap Log:

hasMap: {Sender=com.dapps.misronim.model.User@692c8cd, Messages=13, SenderUID=l091zJ6QLuUksQatElaA4dScHwh2}

HashMap log is working, but when I try to return it,it just return null.

Thanks to all the helpers !

HoLoGram
  • 113
  • 7
  • I think that this article, [How to read data from Cloud Firestore using get()?](https://medium.com/firebase-tips-tricks/how-to-read-data-from-cloud-firestore-using-get-bf03b6ee4953) might also help you understand the concept. – Alex Mamo Feb 14 '22 at 12:33

0 Answers0