简体   繁体   English

在 Kotlin 中从 Firebase Firestore 获取一个 Object

[英]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.我想从 Firebase Firestore 获取一个 Object,但我无法操纵我收到的 object。 How can I separate the imageLink from the imageTitle ?如何将imageLinkimageTitle分开?

The database structure is:数据库结构为: 数据库结构

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:但是,当我这样做时,我会收到类似的信息: 我收到的数据

How can I get the imageLink from the imageTitle separately?如何分别从imageTitle获取imageLink

You can try casting imageData as a Map as shown below:您可以尝试将imageData转换为Map ,如下所示:

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.查看let文档以获取更多信息。


You are calling get() on a CollectionReference that will fetch all documents from the collection (if you add any).您正在CollectionReference上调用get() ,它将从集合中获取所有文档(如果您添加任何文档)。 If you only want to fetch 1st document from the collection, you can add limit(1) that'll save any additional charges.如果您只想从集合中获取第一个文档,您可以添加limit(1)以节省任何额外费用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM