Implement Facebook Like Button
Solution 1:
Unlike webpages, you cannot add a Facebook Like button to an Android app. However, you can add the function to Like a post (a Comment in your case) by using "POST" or a "DELETE" query to the Facebook API:
Here is a complete functioning example of what I do to Toggle the Like Status of a Comment in my application:
NOTE: This code is for the older v2.x SDK. So you will need to adapt a few things that are specific to the latest v3.x SDK
On the onClickListener you will use to post / remove a Like, run this piece of code:
try {
String query = "SELECT user_likes FROM comment WHERE post_id= \'"
+ THE_COMMENT_ID + "\'";
Bundle params = new Bundle();
params.putString("method", "fql.query");
params.putString("query", query);
String fqlResponse = Utility.mFacebook.request(params);
JSONArray JALikes = new JSONArray(fqlResponse);
for (int j = 0; j < JALikes.length(); j++) {
JSONObject JOTemp = JALikes.getJSONObject(j);
if (JOTemp.has("user_likes")) {
String userLikeStatus = JOTemp.getString("user_likes");
if (userLikeStatus.equals("true")) {
try {
Bundle parameters = new Bundle();
Utility.mFacebook.request(arrayComments.get(position).getCommentID() + "/likes", parameters, "DELETE");
// CHANGE THE TEXT OF THE WIDGET TO SHOW THE TOGGLED STATE
}
catch(Exception e) {
e.printStackTrace();
}
} elseif (userLikeStatus.equals("false")) {
try {
Bundle parameters = new Bundle();
Utility.mFacebook.request(arrayComments.get(position).getCommentID() + "/likes", parameters, "POST");
// CHANGE THE TEXT OF THE WIDGET TO SHOW THE TOGGLED STATE
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
In the first part of the code (before the for loop
), I check the current status if the Logged in user likes the Comment. Based on the result (in the for loop
), I either remove the Like or I post a Like.
Although it is an older SDK, the code is still valid, and with a few modifications (if necessary) will work just fine.
Post a Comment for "Implement Facebook Like Button"