Web Development Web Development - 1 year ago 1138
Android Question

How to use the Facebook Graph Api Cursor-based Pagination

I didn't find any help on this topic. The Docs say

Cursor-based pagination is the most efficient method of paging and should always be used where possible - a cursor refers to a random string of characters which mark a specific item in a list of data. Unless this item is deleted, the cursor will always point to the same part of the list, but it will be invalidated if an item is removed. Therefore, your app shouldn't store any older cursors or assume that they will still be valid.

When reading an edge that supports cursor pagination, you will see the following JSON response:

"data": [
... Endpoint data is here
"paging": {
"cursors": {
"after": "MTAxNTExOTQ1MjAwNzI5NDE=",
"before": "NDMyNzQyODI3OTQw"
"previous": "https://graph.facebook.com/me/albums?limit=25&before=NDMyNzQyODI3OTQw"
"next": "https://graph.facebook.com/me/albums?limit=25&after=MTAxNTExOTQ1MjAwNzI5NDE="

I am using this format to make an api call, how can i go through all pages in a loop

/* make the API call */
new GraphRequest(
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */

Answer Source

I figured out a good way to traverse through facebook graph api pages using cursor pagination

    final String[] afterString = {""};  // will contain the next page cursor
    final Boolean[] noData = {false};   // stop when there is no after cursor 
    do {
        Bundle params = new Bundle();
        params.putString("after", afterString[0]);
        new GraphRequest(
                personId + "/likes",
                new GraphRequest.Callback() {
                    public void onCompleted(GraphResponse graphResponse) {
                        JSONObject jsonObject = graphResponse.getJSONObject(); 
                        try {
                            JSONArray jsonArray = jsonObject.getJSONArray("data");

                            //  your code 

                            if(!jsonObject.isNull("paging")) {
                                JSONObject paging = jsonObject.getJSONObject("paging");
                                JSONObject cursors = paging.getJSONObject("cursors");
                                if (!cursors.isNull("after"))
                                    afterString[0] = cursors.getString("after");
                                    noData[0] = true;
                                noData[0] = true;
                        } catch (JSONException e) {
    while(!noData[0] == true);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download