简体   繁体   中英

How to get all data at each month from Firebase for calculation in Android

There are multiples dates and data for each date. Each date and data store under a unique key.

"Data":{
   "K2ngvpioRUYF4bRM07Da5cbAjE53":{
      "-M3jNjCuGdMCwt1Czpwz":{
         "Date":"2020-3-30",
         "Scale":"3"
      },
      "-M3jQWxm7z0EQYgkVenX":{
         "Date":"2020-4-29",
         "Scale":"4"
      },
      "-M5hxn-rCJICUvRcMZJu":{
         "Date":"2020-4-24",
         "Scale":"2"
      }
   }
}

I would like to calculate the total number of scales for monthly (The main point is monthly). Instead of using "startAt" and "endAt":

   Query query = ref.orderByChild("Date").startAt("2020-3-1").endAt("2020-3-31");
   Query query2 = ref.orderByChild("Date").startAt("2020-4-1").endAt("2020-4-30");

Is there any better way to loop for all month and year? I think the above code is hard if I have dates of different years and months.

If your ref object is pointing to the database root, then your reference is not correct since you are missing the Data and the ID of the user from it. See the Data and the K2ngvpioRUYF4bRM07Da5cbAjE53 are present in your tree? Both children should be added to your query. Besides that, you are using for the Date property, String values which is actually also not correct. You should use a Timestamp, as explained in my answer from the following post:

That being said, a correct query should look like this:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query query = ref.child("Data").child(uid) //Added both children
    .orderByChild("Date")
    .startAt(startLongValue)
    .endAt(endLongValue);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM