How to use the Facebook Graph Api Cursor-based Pagination

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(
                accessToken,
                personId + "/likes",
                params,
                HttpMethod.GET,
                new GraphRequest.Callback() {
                    @Override
                    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");
                                else
                                    noData[0] = true;
                            }
                            else
                                noData[0] = true;
                        } catch (JSONException e) {
                            e.printStackTrace(); 
                        }
                    }
                }
        ).executeAndWait();
    }
    while(!noData[0] == true);

Do not reinvent the wheel.

GraphResponse class already has a convenient method for paging. GraphResponse.getRequestForPagedResults() returns GraphRequest object, and you can use that object for paging.

Also I found code snippet from facebook-android-sdk's unit test code.

GraphRequest nextRequest = response.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT);
nextRequest.setCallback(request.getCallback());
response = nextRequest.executeAndWait();