Antony Lajes
Antony Lajes

Reputation: 71

Get an Object from Firebase Firestore in Kotlin

I alredy searched here in the forum but i didn't find nothing like that. I want to get an Object from Firebase Firestore, but I can't manipulate the object that I am receiving. How can I separate the imageLink from the imageTitle?

The database structure is: Database Structure

The code I am using is:

firebaseFirestore.collection("image").get()
            .addOnSuccessListener { documentSnapshot ->
                val imageData = documentSnapshot.documents[0].data?.getValue("imageData")
            }

But, when I do that, I receive something like that: Data that I'm receiving

How can I get the imageLink from the imageTitle separately?

Upvotes: 0

Views: 68

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50830

You can try casting imageData as a Map as shown below:

db.collection("images").limit(1).get().addOnSuccessListener { querySnapshot ->
    val imageData =
        querySnapshot.documents[0].data!!.getValue("imageData")?.let { it as Map<*, *> }

    val imageLink = imageData?.get("imageLink")
    val imageTitle = imageData?.get("imageTitle")

    Log.d("MainActivity", "imageLink: $imageLink")
    Log.d("MainActivity", "imageTitle: $imageTitle")
}

Checkout the documentation for let for more information.


You are calling get() on a CollectionReference that will fetch all documents from the collection (if you add any). If you only want to fetch 1st document from the collection, you can add limit(1) that'll save any additional charges.

Upvotes: 1

Related Questions