Hey I'm developing an app which will show latest data which I add on firebase database on daily basis. Most recent data should appear on top in recyclerview. Here is how the the nodes look like on firebase
Lets assume that currently there are 100 nodes in the database. When the app opens it gets the data stores in nodes 100 to 80. When the user scrolls down it gets more latest data stored in node 79 to 59 and so on.
Right now I'm able to get the last 20 nodes with this query
Query jokesQuery = FirebaseDatabase.getInstance().getReference().child("hindi-jokes").orderByKey().limitToLast(20);
I can get the key of the node at position 79 if I modify the query to limit to last 21 items but how do I then use the 79th nodes key to get the next set of node data i.e from 79th to 59th ?
You'd use endAt()
, since you want the last item to be returned to be the "oldest" one that you got before.
DatabaseReference jokesRef = FirebaseDatabase.getInstance().getReference().child("hindi-jokes");
Query jokesQuery = jokesRef.orderByKey().endAt(oldestKeyYouveSeen).limitToLast(20);
The oldestKeyYouveSeen
is known as the anchor. You need to track this yourself in your code: setting it to the key of the oldest item that you'd you've seen.
Note that it will be both in the first query and in the second, so you'll have to explicitly exclude it once in your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With