Retrieving data with pagination

suggest change

When you have a huge JSON database, adding a value event listener does not make sense. It will return the huge JSON and parsing it would be time consuming. In such cases we can use pagination and fetch part of the data and display or process it. Kind of like lazy loading or like fetching old chats when the user clicks on show older chat. In this case Query can be used.

Let’s take our old example in previous sections. The user base contains 3 users. If it grows to, say, three hundred thousand users and you want to fetch the user list in batches of 50:

// class level
final int limit = 50;
int start = 0;

// event level
Query userListQuery = userDBRef.orderByChild("email").limitToFirst(limit)
        .startAt(start);
userListQuery.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // Do something
        start += (limit+1);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // Do something about the error
    }
});

Here value or child events can be added and listened to. Call the query again to fetch the next 50. Make sure to add the orderByChild() method; this will not work without that. Firebase needs to know the order by which you are paginating. start is an int, so startAt(start) is the double overload, not a row offset, and it does not match string email keys. The snippet never builds a new query after start changes.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents