如何解析Facebook的下一页(SDK 4.0)android中的图形响应?

时间:2015-07-14 05:15:27

标签: android facebook facebook-graph-api facebook-sdk-4.0 facebook-graph-api-v2.3

我正在获取使用我的Android应用程序并在listview中显示它们的朋友列表。我们从电话中得到的回复:

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



                    }
                }
        ).executeAsync();

 {
  "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
  }
}

现在我们如何在android中解析结果的下一页,因为它是下一页的链接?下一页api调用只能通过图形api或facebook完成吗?

2 个答案:

答案 0 :(得分:10)

ifaour有正确的想法如何使用下一个分页,虽然我认为他是对的我只想添加一个递归方式将页面后面的所有结果提取到一个不错的列表对象中,这是来自项目请求用户照片,但它的想法和语法与喜欢的相同(请注意,这一切都是使用执行和等待,所以你必须从一个单独的线程运行它,否则你将有效地阻止你的UI线程,并最终使应用程序自行关闭。

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();
        }
    }
};

现在你需要做的只是做出初始请求并设置你在上一步中做过的回调,回调将处理调用其余项目的所有脏工作,这最终会给你您请求中的所有项目。

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

答案 1 :(得分:2)

如@CBroe所述,您使用getRequestForPagedResults方法。例如,检查Scrumptious示例项目。

我扩展了HelloFacebookSample并添加了两个按钮,用于加载初始用户喜欢的页面,另一个按钮将加载下一个结果(如果可用):

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();
    }
  }
});

现在从LoginManager成功回调中调用handlePendingAction()。正如您所看到的,我有一个额外的动作LOAD_LIKES将触发一个方法,该方法将执行以下操作:

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);

现在我的loadNextLikesButton回调如下:

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;
}

不太漂亮,但你明白了。