Search code examples
javafirebaseandroid-studiofirebase-realtime-databaseandroid-calendar

Retrieve firebase data within a range of 1 week


I want to retrieve Firebase data within a range of say 1 week. I can query and get data for a day like today, but how about for a range of say 1 week? This is the code that am currenly using for retrieving data for a given day

String mDate = DateFormat.getDateInstance().format(new Date());
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference("expenses").child(onlineUserId);
    Query query = reference.orderByChild("date").equalTo(mDate);
    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            myDataList.clear();
            for (DataSnapshot snapshot :dataSnapshot.getChildren()){
                Data data = snapshot.getValue(Data.class);
                myDataList.add(data);

            }
            todayItemsAdapter.notifyDataSetChanged(); 
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

I cannot find a way of retrieving data for a given range. Someone please help. enter image description here


Solution

  • The Realtime Database is not designed for complex SQL-like queries.

    Not sure if your question refers to grouping results by week. If all you need is a set of results that start and on a certain date and end on another date, you can use startAt(...) and endAt(...) like described in this answer or the spec.

    If you need anything more complex than that, you need to

    1. either take all results and filter them in your front end/app code

    2. or use a Cloud Function to do the filtering on the server and passing the results to the front end.

    3. (Not recommended) You can record the week number (i.e. 45_2020) as a separate field in the document, and filter by that. It's messy and you would have to trust that the front end enters correct info in the field.