0

I'm using Firestore as a database and RecyclerView combined with FirestorePagingAdapter to present data in my Android app.

Data presented is sorted by date and I'd like to set default start position for RecyclerView to show a recent object. Currently, by default it shows the first one, which in my case is the oldest one. This is problematic for a long list, as user has to scroll down for a long time.

Is it possible to somehow override this behavior?

EDIT 1: I already sort data by date, but I'd like to start from objects in the middle (e.g. from the current month) and have ability to scroll backward and forward. For example imagine list of movies - you want to see recent ones and have ability to scroll to older and newer ones.

Filip
  • 573
  • 5
  • 19

1 Answers1

1

Yes, it's possible. You have three ways in which you can achieve this. The first one would be to add a date to your items and then query the database according to it. To achieve this, you should use a query that looks like the following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
Query query = collection("items").orderBy("date", Query.Direction.ASCENDING);

You can pass as the second argument the direction, which can be ASCENDING or DESCENDING, according to your needs.

The second approach would be to reverse the order of your RecyclerView using the following lines of code:

LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager)

And the third approach would be to verride the getItem() method to invert the item lookup like this:

@Override
public HashMap getItem(int pos) {
    return super.getItem(getCount() - 1 - pos);
}

One more thing to note, the FirestorePagingAdapter in the FirebaseUI library is designed to get data, not to listen for realtime updates.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Is there everything alright, have you solved the problem? – Alex Mamo Jun 16 '18 at 09:16
  • Sorry for the late response! I already have the date field and I'm sorting by it. But my problems is the following - even though I have objects spanning from 1 year ago to 1 year in the future, I'd like to always start with current ones (let's say from the current month). This would mean user can scroll back and forward. – Filip Jun 19 '18 at 19:48
  • This is basically another question. Don't edit a question by adding another question, just post another fresh question, so me and other users can help you. My personal hint is to use a query with ranges. – Alex Mamo Jun 20 '18 at 06:58
  • If you think that my answer helped you for the initial question, please consider accepting it. Thanks! – Alex Mamo Jun 20 '18 at 06:59