0

I have a function in my firebase class that returns the username when the UserID is provided to it.

fun getUserName(userID: String): String? {
        var userName: String? = null
        mFireStore.collection(Constants.USERS)
            .whereEqualTo(Constants.ID, userID)
            .get() // Will get the documents snapshots.
            .addOnSuccessListener { document ->
                for (i in document.documents) {

                    val user = i.toObject(User::class.java)!!
                    userName = user.userName
                    Log.e("userName", userName!!)
                }

            }
        return userName
    }

The function is not returning the username.

Although I am getting the correct username in the Log entry.

Jazim
  • 1
  • 2
  • There is no way you can do that. 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 16 '22 at 07:57
  • @AlexMamo I think you've pulled the trigger on this too early, as use of [`onSuccessTask`](https://developers.google.com/android/reference/com/google/android/gms/tasks/Task#onSuccessTask(com.google.android.gms.tasks.SuccessContinuation)) would correctly transform the result as OP is expecting which we've both covered in a [previous answer here](https://stackoverflow.com/a/68398645/3068190). – samthecodingman Jun 16 '22 at 08:03
  • @samthecodingman Hey Sam. That's correct. I just added [the previous answer](https://stackoverflow.com/questions/68397179/how-to-retrieve-the-data-that-inserted-in-the-map-firebase-fire-store/68398645#68398645), to the duplicate list. – Alex Mamo Jun 16 '22 at 10:45

0 Answers0