[英]How to retrieve data from firestore and store it to array (Kotlin- Android Studio)
[英]How to retrieve data from nested array of maps in Firestore (Kotlin) for RecyclerView
我想尋求幫助,了解如何從 Firestore 中檢索名為“城市”的嵌套地圖數組到 MutableList 中的數據,然后我想將其插入到回收器視圖中,其中來自“區域”的數據用於 header 和數據常規列表項的“城市”。
區域數據:MutableList,當我按照程序https://medium.com/firebase-tips-tricks/how-to-map-an-array-of-objects-from-cloud-firestore-to-a-list Alex Mamo的 -of-objects-122e579eae10 ,沒問題,但數據:城市:MutableList,根據相同的方法,是 null(無法檢索)。
你能告訴我如何獲取“城市”的數據嗎?
Ps 在某處我閱讀了迭代“城市”的建議,但我不知道如何,請直接向 go 舉個例子(最好是在 Kontlin)。
代碼:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
…..
regionsRef.get().addOnCompleteListener { document ->
if (document.isSuccessful()) {
val documentSnapshot = document.result
// Retrieve array of maps for „regions“
val regions = documentSnapshot.toObject(RegionDocument::class.java)?.regions
// Retrieve array of maps for „cities“
val cities = documentSnapshot.toObject(CityDocument::class.java)?.cities
…
}
}
object 城市的數據類:
data class City(
val cityNumber: Long? = null,
val cityName: String? = "" )
data class CityDocument(
var cities: MutableList<City>? = null)
Firestore結構:
為了能夠獲取與您的文檔結構相對應的數據,您需要三個類:
class Document {
var regions: MutableList<Region>? = null
}
class Region {
var cities: MutableList<City>? = null
var regionName: String? = null
var regionNumber: Long? = null
}
class City {
var cityName: String? = null
var cityNumber: Long? = null
}
在下面您可以找到讀取所有城市的解決方案:
val db = FirebaseFirestore.getInstance()
val docIdRef = db.collection("collName").document("docId")
docIdRef.get().addOnCompleteListener { task ->
if (task.isSuccessful) {
val document = task.result
if (document != null) {
val doc = document.toObject(Document::class.java)
if (doc != null) {
val regions = doc.regions
if (regions != null) {
for (region in regions) {
val cities = region.cities
//Do what you need to to do with your List<City>.
}
}
}
}
} else {
Log.d("TAG", task.exception!!.message!!) //Never ignore potential errors!
}
}
現在,只需將collName
和docId
替換為數據庫中的那個即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.