簡體   English   中英

如何對 firebase android studio 中的多個值求和

[英]how to sum multiple values from firebase android studio

我有carts集合,它包含CartItems作為文檔, CartItemsquantity 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM