How to know whether liked the post or not without

2020-07-19 03:52发布

问题:

I tried to use the fql query to get json response,I used this code for doing this

   String postid=jsonObject.getString("id");

   String query = "SELECT likes.user_likes FROM stream WHERE post_id = \'" + postid + "'";

    Bundle params = new Bundle();
   params.putString("method", "fql.query");
    params.putString("query", query);

   String fqlResponse = Utility.mFacebook.request(params);

   System.out.println(fqlResponse);

But I am getting null pointer exception at Utility.mFacebook.request(params);

I am using the default class in Github

回答1:

I personally find the Facebook Graph API a little inadequate at times. For example, in your current requirement, if you need to use just the Graph API, you will need to first, get a list of all Users who have liked a particular post. After you have a list, you will then have to check if the User ID matches that of the logged in User and then, based on the result, run a function or something.

Instead, FQL offers a simpler function. In my app, for the exact same function, I exclusively make use of FQL.

You can fire a simple query. For example:

SELECT likes.user_likes FROM stream WHERE post_id ='XXXXXXXXXXXXX_XXXXXXXXX'

Replace the X's with the Post's ID. Make sure you surround the Post ID with 'YOUR_POST_ID'

Try it like this in the Graph API Explorer: fql?q=SELECT likes.user_likes FROM stream WHERE post_id = 'ENTER_YOUR_POST_ID'

After running the query, you should get a result that looks this this:

{
  "data": [
    {
      "likes": {
        "user_likes": true
      }
    }
  ]
}

If the User likes the Post, the field user_likes will be true and false if the User has not liked the Post.

You can parse the result like this (pseudo code):

if (JOLikeStatus.has("likes")) {
    JSONObject optLikes = JOLikeStatus.optJSONObject("likes");

    if (optLikes.has("user_likes")) {
        String getUserLikes = optLikes.getString("user_likes");

        if (getUserLikes.equals("true")) {
            String getLikeStatus = "true";
        } else if (getUserLikes.equals("false")) {
            String getLikeStatus = "false";
        }
    } else {
        String getLikeStatus = null;
    }
} else {
    String getLikeStatus = null;
}

EDIT 2: To get the number (count) of total likes, modify the earlier query like this: fql?q=SELECT likes.user_likes, likes.count FROM stream WHERE post_id = 'ENTER_YOUR_POST_ID'