0

I have a function that retrieves data from Firebase. When it retrieved data ı store that data with for loop in a string variable. But when i tried to use that string variable that function returns an empty string. I know that for loop is working async but ı can 't handle the storing data in string variable async too. Appreciated for any help.


fun getUser() : String{
        var username: String =""

                val docRef = database.collection("Users").whereEqualTo("email", currentUserEmail!!)

                docRef.get().addOnSuccessListener {

                    val documents= it.documents

                    for (document in documents){

                        username=document.get("userName") as String

                    } 
                } 
        return username
    }
}
Frank van Puffelen
  • 499,950
  • 69
  • 739
  • 734
  • There is no way you can return the `username` as a result of a method. Firebase API is asynchronous. So please check the duplicate to see how can you solve this using a callback. You might also be interested in reading this [resource](https://medium.com/firebase-tips-tricks/how-to-read-data-from-cloud-firestore-using-get-bf03b6ee4953). – Alex Mamo Jun 05 '22 at 07:49

0 Answers0