Filip
Filip

Reputation: 605

Set start position in my RecyclerView when using FirestorePagingAdapter

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.

Upvotes: 0

Views: 1426

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 139019

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.

Upvotes: 1

Related Questions