【问题标题】:Retrieve map inside map Kotlin在地图 Kotlin 中检索地图
【发布时间】:2019-07-23 09:57:22
【问题描述】:

我的数据结构为:

        val drinks = hashMapOf(
        "cola" to hashMapOf(
            "price" to 36,
            "amount" to 15
        )
    )

我使用 firestore 并想检索价格。

        db.collection("category").document("drinks").get()
        .addOnSuccessListener {documentSnapshot->
            documentSnapshot.data?.forEach {
            //it ->  Map.Entry<String!,Any!>
                Log.d(TAG, "for each data: ${it.key} ${it.value}")
            }
            if (documentSnapshot != null && documentSnapshot.exists()) {
                Log.d(TAG, "read data: ${documentSnapshot["sultan"]}")
            } else {
                Log.d(TAG, "Current data: null")
            }
    }

我尝试将其转换为对象列表,但没有任何帮助

【问题讨论】:

  • 请将您的数据库结构添加为屏幕截图并指明您想要获取的确切数据。也请回复@AlexMamo

标签: android kotlin google-cloud-firestore


【解决方案1】:

在 kotlin 中使用 Firebase 处理数据的更好方法。

.addOnSuccessListener { docsSnapshot ->
    for (docSnapshot in docsSnapshot.documents) {
        val hashmap = docSnapshot.data
        hashmap?.put("id", docSnapshot.id)
        Log.e("hashmap", hashmap) // This hashmap holds your document id and rest of data.
        val Data = Gson().toJson(hashmap)
        val docsData = Gson().fromJson<Drinks>(Data, Drinks::class.java)
        Log.e("docsData", docsData) // Now you can access what type of data you need.
    }
}

POKO 为您提供数据:

class Drinks{
    val id : String,
    val amount : Long,
    val price : Long,
}

【讨论】:

  • 我喜欢这种方法,但它不起作用,你能帮帮我吗?
  • 请以适当的方式发布您的问题以了解什么不起作用?
  • Log.e("hashmap", hashmap) 返回:{sprite={amount=60, price=89}, id=drinks, cola={amount=15, price=36}}但是 Log.e("docsData", docsData) 返回: Products(list=[])。我的数据类是这样的: 数据类 Product(var amount:Long = 0, var price: Long = 0L) 数据类 Products(var list:List = emptyList())
  • @Nurseyit 请pojo你试过它需要是这样的
猜你喜欢
  • 2020-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 2012-03-26
  • 2021-04-20
  • 2018-03-03
相关资源
最近更新 更多