Is there a way in firebase android to fetch data within a range?

Tags: , , ,



I have a database in firebase realtime database.My DB look like this :

enter image description here

I want to fetch data within a date range. That is if user select 03-09-2020 as start date and 05-09-2020 as end date,what i want is to display all values of TotalTax field (in this case 3 values 500,500 and 100). How can i achieve this? Hope you understand me :).

Answer

Your date format does not allow fetching a range of dates, since the range is not sequential. Say you’d want to retrieve the nodes for the first three days of September, in your current format that’d look like this:

/// THIS DOES NOT WORK
ref.orderByChild("Date").startAt("01-09-2020").endAt("03-09-2020")

But this won’t work because the values are not lexicographically sorted.

To allow retrieving the nodes on a range of dates, store those values in a format where the lexicographical order is the same as the chronological order. So: "2020-09-05" for September 5th.

With that date format, you can then query for the date range with:

ref.orderByChild("Date").startAt("2020-09-01").endAt("2020-09-03")


Source: stackoverflow