问题描述:

I am writing an android chat app and I am trying to implement endless scrolling using Firebase Database in RecyrclerView using custom FirebaceRecyclerAdapter. For first messages load I get data from Firebase Database by using query that ordering data by .orderByChild() and then .limitToFirst(specificCount) so far so good. But when user scrolled to the last visible item I have to get next portion of messages and the problem comes I did not get a straight way to get messages from Firebase Database after specificCount. I tried with that code:

 int startCount = mLayoutManager.getItemCount();

FirebaseDatabase

.getInstance()

.getReference()

.child(RequestParameters.FB_CHILD_MESSAGES)

.orderByChild(RequestParameters.FB_CHILD_MESSAGES_ORDERING_TIME)

.startAt(startCount)

.endAt(startCount + CustomFirebaceRecyclerAdapter.NEXT_MESSAGE_PORTION_COUNT)

.addListenerForSingleValueEvent(...)

But after I read the documentation for .startAt() I realize how stupid is this. Anyone could help to make a query that gets items after specificCount and limit received messages to some count.

网友答案:

I'm pretty sure I answered this less than a day ago, so I recommend scanning my answers. But I'll repeat.

The Firebase Database API is inherently not very well suited for pagination. Think of what happens when an item is inserted while the user is on page 1 (with the first ten items). They end up seeing the previous item 10 at the start of page 2, but will never have seen the newly inserted item.

That said, if you want to do pagination, it is technically possible. But instead of wanting to skip 10 items, you will instead have to tell Firebase to start the query at the last item from the previous page. This is called an anchor item and in code it looks like this:

FirebaseDatabase
        .getInstance()
        .getReference()
        .child(RequestParameters.FB_CHILD_MESSAGES)
        .orderByChild(RequestParameters.FB_CHILD_MESSAGES_ORDERING_TIME)
        .startAt(timeOfLastItemOnPreviousPage, keyOfLastItemOnPreviousPage)
        .addListenerForSingleValueEvent(...)

The key properties here are:

  • timeOfLastItemOnPreviousPage: the value of the FB_CHILD_MESSAGES_ORDERING_TIME property of the last item on the previous page

  • keyOfLastItemOnPreviousPage, the key of the last item on the previous page (which is needed in case there are multiple items with the same value for FB_CHILD_MESSAGES_ORDERING_TIME

相关阅读:
Top