GetValue Firebase

时间:2018-01-10 14:24:51

标签: android firebase firebase-realtime-database

我有一个firebase结构如下:

Orders
  HALa1r5un1gkcddZzzDRQWxPCwm2 //This is the UserUID
    1515589315695                //This is This is the order code
      total : 4000                  //This is the total order amount

    1515592859285
      total : 2000

如何获得上述两个订单的总金额。结果将是:6000

我有另一个问题。收到6000结果后,如何将6000转换为60?我想从一个有数千的数字转变为数十个数字 示例:1000 - > 10

1 个答案:

答案 0 :(得分:1)

假设Orders节点是Firebase root的直接子节点并且total声明为int类型,要解决此问题,请使用以下代码:

String uid = firebaseAuth.getCurrentUser().getUid();

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Orders").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int sum = 0;
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            int total = ds.child("total").getValue(Integer.class);
            sum = sum + total;
        }
        Log.d("TAG", sum);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);

输出为:6000

要将6000转换为60,只需将sum除以100,或者查看Java NumberFormat