简体   繁体   中英

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) {

        }
    });
}

I think you can use 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM