使用Kotlin协程仍然没有文档

问题描述 投票:0回答:1

我正在使用 Kotlin 协程,但 Log.d("Products", products.toString()) 仍然返回空。我尝试在 toast 中检查结果的大小,但结果为 0。任何人都可以检查并告诉我为什么会发生这种情况,并且 logcat 也没有显示错误。

搜索项目活动

import android.os.Bundle
import android.util.Log
import android.widget.GridView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.Firebase
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.firestore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await

class SearchItemActivity : AppCompatActivity() {
    private val db = Firebase.firestore
    private val products: MutableList<DocumentSnapshot> = mutableListOf()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search_item)

        val gridView = findViewById<GridView>(R.id.itemGridView)

        CoroutineScope(Dispatchers.Main).launch {
            try {
                val result = db.collection("product").get().await()
                Toast.makeText(this@SearchItemActivity, "Number of documents in 'product' collection: ${result.size()}", Toast.LENGTH_SHORT).show()
                for (document in result) {
                    val uid = document.id
                    val results = db.collection("product").document(uid).collection("products").get().await()
                    products.addAll(results.documents)
                }
                val adapter = ItemUserAdapter(this@SearchItemActivity, layoutInflater, products)
                gridView.adapter = adapter
            } catch (e: Exception) {
                Toast.makeText(this@SearchItemActivity, e.localizedMessage, Toast.LENGTH_SHORT).show()
            }
        }

        Log.d("Products", products.toString())

        gridView.setOnItemClickListener { parent, view, position, id ->
            val product = parent.getItemAtPosition(position) as DocumentSnapshot
            Toast.makeText(applicationContext, "UID: ${product.id}", Toast.LENGTH_SHORT).show()
        }
    }
}

firestore结构是这样的-

android firebase kotlin kotlin-coroutines android-gridview
1个回答
0
投票

当使用以下代码行时:

val result = db.collection("product").get().await()

这意味着您想要阅读名为 product

top-level
集合中存在的所有文档。但是,据我在您的屏幕截图中看到的,这些产品存在于一个名为
products
的子集合中。如果您需要获取单个文档的
products
子集合中存在的产品,那么您必须创建一个指向该子集合的引用:

val result = db.collection("product")
               .document("5s8Q...z4T") //👈
               .collection("products") //👈
               .get()
               .await()

如果您需要获取所有子集合中的所有产品,那么您可以使用集合组查询,如下所示:

val result = db.collectionGroup("products") //👈
               .get()
               .await()
© www.soinside.com 2019 - 2024. All rights reserved.