简体   繁体   English

如何对 firebase android studio 中的多个值求和

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

I have carts collection and it contains CartItems as document, CartItems have quantity field I want to SUM them, I wrote this code but the return type should be List<CartItem> how I can change it to Int and return totalQuantity value我有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
                }

            }
        }
}

Haven't test it but it should do the job:还没有测试过,但它应该可以完成工作:

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