![](/img/trans.png)
[英]How to count the specific values from firebase in android studio?
[英]how to sum multiple values from firebase android studio
我有carts
集合,它包含CartItems
作为文档, CartItems
有quantity field
我想对它们求和,我写了这段代码但返回类型应该是List<CartItem>
如何将它更改为Int
并返回totalQuantity
值
suspend fun getTotalQuantity(userID: String): Int {
var totalQuantity = 0
CartRepository.usersDocumentRef
.document(userID)
.collection("carts")
.get()
.addOnCompleteListener { task ->
if (task.isSuccessful) {
task.result.toObjects(CartItem::class.java).forEach {
totalQuantity += it.quantity
}
}
}
}
还没有测试过,但它应该可以完成工作:
suspend fun getTotalQuantity(userID: String): Int {
var totalQuantity = 0
CartRepository.usersDocumentRef
.document(userID)
.collection("carts")
.get()
.addOnCompleteListener { task ->
if (task.isSuccessful) {
for (i in task.result.documents) {
totalQuantity += i.toObject(CartItem::class.java)!!.quantity
}
// print or use totalQuantity here
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.