android - 尝试检索列表时出现 Cloud Firestore 错误
问题描述
我开始在个人项目中使用 Cloud Firestore,并且在尝试从文档中检索列表时遇到了问题,而我仍然设法从后端接收了一些数据,但在检查数据库时并不那么精确。
Collection
DocumentN
-otherStuff
-usermatches: <---- This is an array
(0):
-Score:0
-Id:123
(1):
-Score:1
-Id:456
架构
我一直在尝试很多,下面的课程是我暂时解决错误 HashMap cannot be cast to parameter..
但我不知道如何真正实现我所需要的,如果您有任何反馈或有任何建议,请告诉我
后端.kt
docRef = db.collection("userdata").document(user.user_id)
docRef.get()
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val document: DocumentSnapshot = task.result
val cedula = document.data!!["cedula"] as Long
val points = document.data!!["points"] as Long
// val usermatches = document.data!!["usermatches"] as HashMap<String, Any>
val alias = document.data!!["username"] as String
// val usermatches = document.toObject(Usermatches::class.java)
val map: MutableMap<String, Any>? = document.data
for (entry in map!!.entries) {
if (entry.key == "usermatches") {
val list = entry.value as ArrayList<Any>
for (each in list){
for (entry2 in each as HashMap<String, Any>){
var home_score: Long = 0
var winner: Long = 0
var userchanged: Boolean = true
var id: String = ""
var away_score: Long = 0
val usermatch = Usermatches(home_score, away_score, id, userchanged, winner)
when {
entry2.key == "away_score" -> {
away_score = entry2.value as Long
usermatch.away_score = away_score
// println(away_score)
}
entry2.key == "home_score" -> {
home_score = entry2.value as Long
usermatch.home_score = home_score
// println(home_score)
}
entry2.key == "id" -> {
id = entry2.value as String
usermatch.id = id
// println(id)
}
entry2.key == "userchanged" -> {
userchanged = entry2.value as Boolean
usermatch.userchanged = userchanged
// println(userchanged)
}
entry2.key == "winner" -> {
winner = entry2.value as Long
usermatch.winner = winner
// println(winner)
}
}
mDisposable.add(usermatchesViewModel.insert(Usermatches(home_score, away_score, id, userchanged, winner))
.subscribeOn(Schedulers.io())
.subscribe{ println("Checking")})
}
}
}
}
} else {
Log.d(TAG, "Error getting Usermatches ", task.exception)
}
}
})
用户匹配数据类
@Entity
data class Usermatches(var home_score: Long,
var away_score: Long,
@ColumnInfo(name = "usermatches_id") var id: String,
var userchanged: Boolean,
var winner: Long) {
@PrimaryKey(autoGenerate = true)
var num_id: Long = 0
}
解决方案
-usermatches: <---- 这是一个数组
不是!确实,如果一个对象作为 a 存储在数据库中array
,则entry.value
返回一个 ArrayList 而不是数组,但在您的情况下,usermatches
它是一个map
包含其他映射的 a 0
,1
等等。这就是为什么您也会收到该错误的原因。因此,为了解决这个问题,您需要对usermatches
map 进行两次迭代,一次是获取地图,第二次是获取这些地图中的值。
推荐阅读
- python - 如何使用 Google Kubernetes Engine 并行下载、转换和上传多个文件?
- solace - Solace 客户端确认重播
- c - 在字符串中查找字符位置的麻烦
- node.js - NestJS(节点) - 按泛型类型验证请求
- java - ExecutorService中isCancelled()返回true的原因
- node.js - couchbase 添加子文档唯一数组值
- php - 如何使用带有 preg_match_all 的正则表达式将字符串按照模式拆分为块
- flutter - SliverList 未在 setState 上更新为新列表
- tesseract - pytesseract.pytesseract.TesseractError: (255, '')
- google-cloud-platform - 无法将数据集上传到 AutoML 自然语言文本分类 GUI