Ad

Firebase Realtime Database - Getting Data Within Time Range

On my Android app, I have a calendar. When I click a date, I want to just show the items from that selected date. In other words, filter all other items out of the RecyclerView adapter and just show the ones for the selected Date.

Currently, when the activity opens, it just displays all items:

Query query = FirebaseDatabase.getInstance().getReference().child(FB_SUBJECTS).child(FB_PACKS)

PagedList.Config config = new PagedList.Config.Builder()
        .setEnablePlaceholders(false)
        .setPrefetchDistance(5)
        .setPageSize(10)
        .build();

//Initialize FirebasePagingOptions
DatabasePagingOptions<FB_Model> options;
options = new DatabasePagingOptions.Builder<FB_Model>()
        .setLifecycleOwner(this)
        .setQuery(query, config, snapshot -> {
            FB_Model model = snapshot.child(FB_PROFILE).getValue(FB_Model.class);
            addMarkerToCalendarView(getMilliFromDate(model.getstart_date()));
            return model;
        })
        .build();

That will return all items at subjects/packs. Then from this query, I get some data from <userId>/profile/, like start_date and end_date, eg subject/packs/001/profile/start_date

Here's some sample data for start_date and end_date:

end_date; "05-04-2019"
start_date: "01-04-2019"

So, my problem is I want to filter these items, BUT I'm using FirebaseRecyclerPagingAdapter but that only pulls down a certain number of items at at time, eg 20. So I can't store all the results in one big list and filter them easily. So I'm relying on some built in functionality of Firebase.

Is it possible to alter my Query to achieve this? I know there's a startAt() and endAt() but not sure if they suit FirebaseRecyclerPagingAdapter.

So really what I need is a SELECT * from profiles where startDate = x and endDate = y;

Is that possible with the realtime DB on Android?

Thanks.

Ad

Answer

Is it possible to alter my Query to achieve this?

Sure it is but with some changes. As I see, you are storing in end_date and start_date properties the date as a literal String and this is not how you deal with dates in Firebase. So you should store the date as a Timestamp, which is basically a number, a long value. To see how you can achieve this, please see my answer from the following post:

In the end, simply pass the needed timestamps to the startAt() and endAt() methods.

I know there's a startAt() and endAt() but not sure if they suit FirebaseRecyclerPagingAdapter.

You can pass to FirebaseRecyclerPagingAdapter any kind of query, including the one that has calls to startAt() and endAt() methods.

Ad
source: stackoverflow.com
Ad