计算firebase日期之间的总金额

时间:2017-08-14 09:56:14

标签: android date firebase firebase-realtime-database

firebase snapshot

我需要计算两个日期(0 + 500)之间的总收入。

//这是我的安卓代码

mDatabase.child(selected_account).orderByChild("Date").startAt(begin_date).endAt(end_date).

        addChildEventListener(new ChildEventListener() {

            @Override
            public void onChildAdded(DataSnapshot snapshot, String s) {



Map<String, Object> newPost = (Map<String, Object>) snapshot.getValue();
                    if (newPost != null) {

                        if (newPost.get("Account") != null & newPost.get("Account") != "") {
                            foodList.add(new TransactionFlow
                                    (newPost.get("Account").toString(),
                                            newPost.get("Amount").toString(),
                                            newPost.get("CashAtHand").toString(),
                                            newPost.get("Variant").toString(),
                                            newPost.get("Date").toString(),
                                            newPost.get("DateTime").toString(),
                                            newPost.get("Description").toString(),
                                            newPost.get("Income").toString(),
                                            newPost.get("Field").toString(),
                                            newPost.get("Organisations").toString(),

                                            newPost.get("Field").toString(),
                                            newPost.get("key").toString(),


                                            snapshot.getKey().toString()));
                        }

                    }

    }
    });

//我需要计算两个日期之间儿童收入的总和。

1 个答案:

答案 0 :(得分:3)

首先,将您的日期存储为时间戳。这将有助于您执行选择和减少。

其次,根据存储时间戳的变量为Firebase编制索引。

Long totalAmount = 0l;
mDatabase.child(selected_account).orderByChild(YOUR_TIMESTAMP_VARIABLE).startAt(YOUR_BEGIN_DATE_TIMESTAMP).endAt(YOUR_END_DATE_TIMESTAMP)
 .addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
   if (dataSnapshot.getValue() != null) {
    for (DataSnapshot child: snapshot.getChildren()) {
     totalAmount += dataSnapshot.child('Income').getValue(Long.class);
    }
    //Once you finish your loop. You can present the result of totalAmount
   }
  }

  @Override
  public void onCancelled(DatabaseError databaseError) {
//Log your error here.
  }
 });