0

Hello friends I'm doing practice about Firestore and Firebase Auth and I wanted to read only one field but I can't do that. It's probably easy but I can't find anything in Internet. Is anyone can help me. Have a good Codes :)


A piece of my code

auth = Firebase.auth

private val db = Firebase.firestore.collection("user")


private fun getPic(){
val pic = db.document(auth.currentUser?.email.toString()).get(..?.) ....?..
}

I wanted to read that URL

I wanted to read that URL

Mert Ozan
  • 29
  • 5
  • Since you're using Kotlin, I think that this [resource](https://medium.com/firebase-tips-tricks/how-to-read-data-from-cloud-firestore-using-get-bf03b6ee4953) will help. – Alex Mamo Dec 01 '22 at 15:21

1 Answers1

1

There is no way to fetch just one field from a Firebase document (https://stackoverflow.com/a/48312562/1896015).

You need to fetch the whole document, which is done asynchronously and then handle the received response, which contains the whole document data.

You also fetch the document from the collection which in this case is user which makes the whole path user/{email}.

From your code example this would probably look like this:

private fun getPic() {
 val docRef = db.collection("user").document(auth.currentUser?.email.toString())
 docRef.get()
        .addOnSuccessListener { document ->
            if (document != null) {
                Log.d(TAG, "picUrl: ${document.data.picUrl}")
            } else {
                Log.d(TAG, "No such document")
            }
        }
        .addOnFailureListener { exception ->
            Log.d(TAG, "get failed with ", exception)
        }
}

In this case you only log the information, but I guess you would want to return the picUrl from the function. I suggest looking in to Kotlin asynchronous functions for different ways to handle this: https://kotlinlang.org/docs/async-programming.html#callbacks

Martin Kjellberg
  • 615
  • 1
  • 6
  • 22