1

In my firebase there are comments -

enter image description here

I want to show them in RecyclerView in descending order. So, as you can see I added "-" in date of every comment.

Then I just used -

query.orderByChild("date").limitToFirst(10);

Which is working fine. But I want to paginate so when user click "load more" it should load more ten. To do that I am storing the last comment Id and tried something like this-

query.orderByChild("date").startAt(lastCommentId).limitToFirst(10);

Its not working and not even generating result. I also tried to alter the position of startAt and orderByChild but got no success. Then I tried something like this-

query.orderByKey().startAt(lastCommentId).limitToFirst(10);

Which works fine but I want to arrange them in order of date. so,

query.orderByKey().startAt(lastCommentId).orderByChild("date").limitToFirst(10);

But this crashes my application. I don't understand why it isn't working. I also tried to alter the position of orderByChild but same result.

Can anybody explain me whats the problem and suggest a better solution to what I am trying to do.

Thanks !

Answer

I did some more research on this topic as this is one of the common problem with firebase. I found this video https://www.youtube.com/watch?v=CH9ptm4NeTw

Hope this helps !

Zicsus
  • 1,115
  • 1
  • 9
  • 19
  • 1
    logcat/stacktrace to see the error? – pleft Oct 08 '17 at 06:34
  • What's the value for `lastCommentId` that you pass in? – Frank van Puffelen Oct 08 '17 at 06:40
  • @pleft the activity in which I am doing this crashes and it starts my main activity again which refreash the logcat – Zicsus Oct 08 '17 at 06:40
  • @FrankvanPuffelen last Id - "-KvrIDhAV4qrMSodrAa7". It is somewhere in middle of the data. – Zicsus Oct 08 '17 at 06:43
  • @Zicsus see here if this helps to see your logcat and update your question with it. https://stackoverflow.com/questions/30113827/android-studio-adb-wipes-out-logcat-files-when-app-crashes-ohh-myy – pleft Oct 08 '17 at 06:43
  • @pleft I did what above solution suggested and logcat give the error that "You can't combine multiple orderBy calls!". But than why it gives me option to add them multiple times? is there another way to do it then ? – Zicsus Oct 08 '17 at 06:56
  • https://stackoverflow.com/a/41041561/3635454 – pleft Oct 08 '17 at 07:04

1 Answers1

0

To get the second page of results you need two things:

  1. the date value to start at
  2. the key of the item to start at

The key is used as a tie breaker in case there are multiple items with the same date.

If you have both your query will look like this:

query.orderByChild("date").startAt(lastDate, lastCommentId).limitToFirst(10);

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807