Firebase to load more items on scroll (Android)

I'm trying to make a chat application, I use Firebase as my backend, I'm populating my listview onCreate() with the last 10 messages sent, and I just want that when the user scrolls up ^ it will load 10 more every time.

I got all working, the problem is that the Firebase loads all the data every time, and not increasing by 10 the existing data.

For example: it loads 10 messages at startup, and when I scroll up it loads 20 messages, and then it loads 30 messages, instead of just loading 10 more at a time.

This is the code:

//Listview to find when user is scrolling and reach the top i.e firstVisibleItem == 0

messagesList.setOnScrollListener(new AbsListView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(AbsListView absListView, int i) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
        int visibleItemCount, int totalItemCount) {

        if (firstVisibleItem == 0 && !loading) {
            msgNum += 10;
            setMessagesList(msgNum); //your load more function
        }
    }
});

//Firebase to load more on scroll code:
public void setMessagesList(int msgNum) {

    MessegesRef2 = database.getReference("chatsMessages").child(chatID);
    messageValueListener = MessegesRef2.orderByChild("creationDate").limitToLast(msgNum).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            loading = true;
            for (DataSnapshot data: dataSnapshot.getChildren()) {

                ChatMessage chatMessage = data.getValue(ChatMessage.class);

                chatMessageAdapter.add(chatMessage);
                chatMessageAdapter.notifyDataSetChanged();
            }
            loading = false;
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

我认为你可以使用endAt()

ref.orderByChild("creationDate").limitToLast(pageSize).endAt(oldestLocalMessageTime).addValueEventListener
// pageSize is the number of messages you want to load each time (10)
// oldestLocalMessageTime is the time of oldest message that you have loaded from Firebase
// everytime you load/load more messages you need to update oldestLocalMessageTime value

you can use startAt(), endAt(), and equalTo() method. When the user reaches the end of the list then call a method to load more from the server. make sure to implements ValueEventListener.

Query pagination = mDatabase.orderByChild("id").startAt(startAt).endAt(startAt + 10);
pagination.addListenerForSingleValueEvent(this);
链接地址: http://www.djcxy.com/p/94482.html

上一篇: 在android工具栏中正确实施SearchView

下一篇: Firebase在滚动中加载更多商品(Android)