I am making android chat app with firebase firestore database a I need infinite pagination with listeners for data changes (new massage, deleted massage...)
I found blog post written in kotlin and of corse searched firebase documentation and end up with this code:
// firstTime variable shows if function is called from pagination or initially
private void addMessagesEventListener(boolean firstTime) {
// get collection
CollectionReference messagesCollection = chatsCollection.document(chat.getId()).collection(Constants.FIREBASE_MESSAGES_PATH);
// create query
Query query = messagesCollection.orderBy("timestamp", Query.Direction.DESCENDING);
// if NOT first time add startAt
if (!firstTime) {
query.startAt(startTimestamp);
}
//limit to 20 messages
query.limit(20).get().addOnSuccessListener(queryDocumentSnapshots -> {
if (!firstTime) {
endTimestamp = startTimestamp;
}
startTimestamp = (long) queryDocumentSnapshots.getDocuments().get(queryDocumentSnapshots.size() - 1).get("timestamp");
Query innerQuery = messagesCollection.orderBy("timestamp").startAt(startTimestamp);
if(!firstTime) {
innerQuery.endBefore(endTimestamp);
}
ListenerRegistration listener = innerQuery
.addSnapshotListener((queryDocumentSnapshots1, e) -> {
if (e != null) {
Log.w(TAG, "listen:error", e);
return;
}
for (DocumentChange dc : queryDocumentSnapshots1.getDocumentChanges()) {
Message message = dc.getDocument().toObject(Message.class);
switch (dc.getType()) {
case ADDED:
// add new message to list
messageListAdapter.addMessage(message);
if (firstTime) {
messagesList.smoothScrollToPosition(0);
}
break;
case REMOVED:
// remove message from list
messageListAdapter.removeMessage(message);
break;
}
}
});
listeners.add(listener);
});
}
Now, code suppose to save listeners 1st for first 20 messages and new messages, 2nd for messages from 20-40 and so on, but, it is not working for some reason. Am I missing something?
Problem is that line
startTimestamp = (long) queryDocumentSnapshots.getDocuments().get(queryDocumentSnapshots.size() - 1).get("timestamp");
gets always the same result. I tried even with documentSnapshot instead of timestamp, same result.
Thanks in advance.
query = query.startAt()
andinnerQuery = innerQuery.startAt()
– Sasa Grujic