![](/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.