How do I parse the following Facebook page (SDK 4.0) Graph response in android?

I collect a list of friends who use an Android app and display them in the list. The response we get from the call is:

 GraphRequestAsyncTask graphRequest = new GraphRequest(
                AccessToken.getCurrentAccessToken(),
                "/me/friends",
                null,
                HttpMethod.GET,
                new GraphRequest.Callback() {
                    public void onCompleted(GraphResponse response) {



                    }
                }
        ).executeAsync();

      

is an

 {
  "data": [
    {
      "name": "Sanjeev Sharma",
      "id": "10XXXXXXXXXX40"
    },
    {
      "name": "Avninder Singh",
      "id": "1XXXXX30"
    },
    {
      "name": "Saikrishna Tipparapu",
      "id": "17XXXXXX98"
    },
    {
      "name": "Perfekt Archer",
      "id": "100XXXXX29"
    },
    {
      "name": "Shathyan Raja",
      "id": "10XXXXX0"
    },
    {
      "name": "Kenny Tran",
      "id": "10XXXXX36164"
    },
    {
      "name": "Lahaul Seth",
      "id": "100XXXXX161"
    },
    {
      "name": "Bappa Dittya",
      "id": "10XXXXX24"
    },
    {
      "name": "Rahul",
      "id": "10XXXXX
    },
    {
      "name": "Suruchi ",
      "id": "7XXXXXXXX11"
    }
  ],
  "paging": {
    "next": "https://graph.facebook.com/76XXXXXXXX28/friends?limit=25&offset=25&__after_id=enc_AdAXXXXX5L8nqEymMrXXXXoYWaK8BXXHrvpXp03gc1eAaVaj7Q"
  },
  "summary": {
    "total_count": 382
  }
}

      

Now how can we parse the next result page in android since it is a link to the next page? Will the next api page call be done with graph api or facebook only?

+3


source to share


2 answers


ifaour has the correct idea on how to use pagination from the next one, although I think he is right, I just wanted to add a recursive way to get the whole results page after page into one fine list object, this is from the project request custom photos, but with same idea and syntax as similar ones (note that this is all used to execute and wait, so you'll have to run this from a separate thread, or effectively block the UI thread and eventually shut down the app itself.

Bundle param = new Bundle();
param.putString("fields", "id,picture");
param.putInt("limit", 100);

//setup a general callback for each graph request sent, this callback will launch the next request if exists.
final GraphRequest.Callback graphCallback = new GraphRequest.Callback(){
    @Override
    public void onCompleted(GraphResponse response) {                       
        try {
            JSONArray rawPhotosData = response.getJSONObject().getJSONArray("data");
            for(int j=0; j<rawPhotosData.length();j++){
                /*save whatever data you want from the result
                JSONObject photo = new JSONObject();
                photo.put("id", ((JSONObject)rawPhotosData.get(j)).get("id"));
                photo.put("icon", ((JSONObject)rawPhotosData.get(j)).get("picture"));

                boolean isUnique = true;

                for(JSONObject item : photos){  
                    if(item.toString().equals(photo.toString())){
                        isUnique = false;
                        break;
                    }
                }

                if(isUnique) photos.add(photo);*/
            }

            //get next batch of results of exists
            GraphRequest nextRequest = response.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT);
            if(nextRequest != null){
                nextRequest.setCallback(this);
                nextRequest.executeAndWait();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
};

      



Now all you have to do is just make the initial request and set the callback you did in the previous step, the callback will handle all the dirty work when calling the rest of the elements, this will eventually give you all the items from your request.

//send first request, the rest should be called by the callback
new GraphRequest(AccessToken.getCurrentAccessToken(), 
        "me/photos",param, HttpMethod.GET, graphCallback).executeAndWait();

      

+10


source


As @CBroe mentioned, you are using the getRequestForPagedResults method . For example, check out the Scrumptious sample project.

I extended HelloFacebookSample and added two buttons that will load the home pages that the user likes, and the other will load the following result if available:

loadAndLogLikesButton = (Button) findViewById(R.id.loadAndLogLikesButton);
loadAndLogLikesButton.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    pendingAction = PendingAction.LOAD_LIKES;
    if (!hasUserLikesPermission()) {
      LoginManager.getInstance().logInWithReadPermissions(HelloFacebookSampleActivity.this, Arrays.asList("public_profile", "user_likes"));
    } else {
      handlePendingAction();
    }
  }
});

      

Now handlePendingAction()

called from the LoginManager success callback. As you can see, I have an additional action LOAD_LIKES

that will call a method that will do the following:



GraphRequest request = GraphRequest.newGraphPathRequest(
  accessToken,
  "me/likes",
  new GraphRequest.Callback() {
      @Override
      public void onCompleted(GraphResponse response) {
          Log.d("HelloFacebook", response.getRawResponse());
          JSONArray data = response.getJSONObject().optJSONArray("data");

          boolean haveData = data.length() > 0;
          if (haveData) {
              loadNextLikesButton.setEnabled(true);
              nextRequest = response.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT);
          }
      }
  }
);

Bundle parameters = new Bundle();
parameters.putString("fields", "id");
parameters.putString("limit", "100");
request.setParameters(parameters);

      

Now my callback loadNextLikesButton

looks like this:

if (nextRequest != null) {
  nextRequest.setCallback(new GraphRequest.Callback() {
    @Override
    public void onCompleted(GraphResponse response) {
      Log.d("HelloFacebook", response.getRawResponse());

      JSONArray data = response.getJSONObject().optJSONArray("data");

      boolean haveData = data.length() > 0;
      if (haveData) {
        loadNextLikesButton.setEnabled(true);
        nextRequest = response.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT);
      } else {
        loadNextLikesButton.setEnabled(false);
      }
    }
  });
  nextRequest.executeAsync();
} else {
  Log.d("HelloFacebook", "We are done!");
  return;
}

      

Not really, but you get the idea.

+2


source







All Articles