1

Here is my code.

fun readNameSurnameByEmail(email: String): String {

    // Сделать чтение для всех данных кроме пароля в разных функциях принимать будет email
    val database = FirebaseFirestore.getInstance()

    val myRef = database.collection("Users").document(email)

    myRef.get()
        .addOnSuccessListener { document ->
            if (document != null) {
                val fieldValue = document.get("name_surname") as String
                Log.d(TAG, "Name and surname successfully read")
            } else {
                Log.d(TAG, "Is empty")
            }
        }
        .addOnFailureListener { exception ->
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, "Error getting document: ", exception)
            }
        }

}

I am creating val fieldValue. How can I return it if it is in SuccessListener?

And another question, is it a correct way of getting a field value by document name?

Here is updated code Is it correct right now?

fun readNameSurnameByEmail(email: String): String {

    // Сделать чтение для всех данных кроме пароля в разных функциях принимать будет email
    val database = FirebaseFirestore.getInstance()

    val myRef = database.collection("Users").document(email)

    var fieldValue = ""
    
    myRef.get()
        .addOnSuccessListener { document ->
            if (document != null) {
                fieldValue = document.get("name_surname") as String
                Log.d(TAG, "Name and surname successfully read")
            } else {
                Log.d(TAG, "Is empty")
            }
        }
        .addOnFailureListener { exception ->
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, "Error getting document: ", exception)
            }
        }
    return fieldValue
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
real4you
  • 31
  • 3
  • There is no way you can return `fieldValue` 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 Dec 23 '22 at 14:17

0 Answers0