[英]How do i sum up values with the same key in firebase database
I'm creating a shopping app where users add items to cart and then I store these values in the Firebase database.我正在创建一个购物应用程序,用户可以在其中将商品添加到购物车,然后我将这些值存储在 Firebase 数据库中。 The problem I've is trying to get the total amount of product added to the cart.
我遇到的问题是试图获取添加到购物车的产品总量。 I have a MapChild with key
productPrice
, now how do I sum up all the data with key productPrice
after saving them in a listmap.我有一个带有键
productPrice
的 MapChild,现在如何在将所有数据保存在列表图中后用键productPrice
总结所有数据。
To sum all the values of the productPrice
property, please use the following lines of code:要对
productPrice
属性的所有值求和,请使用以下代码行:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference cartItemsRef = rootRef.child("cartItems");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long total = 0;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String productPrice = ds.child("productPrice").getValue(String.class);
total += Long.parseLong(productPrice);
}
Log.d("TAG", "total: " + total);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
cartItemsRef.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be: logcat 中的结果将是:
total: 730
If you need to store prices, it's best to store them as numbers and not as String values, as you do right now.如果您需要存储价格,最好将它们存储为数字而不是字符串值,就像您现在所做的那样。 If you intend to change that, then you should simply use:
如果你打算改变它,那么你应该简单地使用:
total += productPrice;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.