How to integrate "Like" and "Comment" feature using Android Facebook SDK? - android

I want to implement "Like" and "Comment" feature in my app. I used this code:
public static void like(String postID) {
String grapPath = String.format("%s/likes", postID);
Request request = new Request(Session.getActiveSession(), grapPath,
null, HttpMethod.POST, new Callback() {
#Override
public void onCompleted(Response response) {
Log.i(TAG, response.toString()+" Success!");
}
});
Request.executeBatchAsync(request);
}
public static void postComment(String comment, String postID) {
String grapPath = String.format("%s/comments", postID);
Bundle bundle = new Bundle();
bundle.putString("message", comment);
Request request = new Request(Session.getActiveSession(), grapPath,
bundle, HttpMethod.POST, new Callback() {
#Override
public void onCompleted(Response response) {
Log.i(TAG, "Success!");
}
});
Request.executeBatchAsync(request);
}
Hhow and where can I call these methods to make them work?

Please make sure the prerequisites are set up correctly. Specifically check out the middle of step 4 to make sure you generated your key hash correctly using your debug keystore.
Otherwise code below should help out
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions");
}
private void postStatusUpdate() {
if (hasPublishPermission()) {
final String message = "Posting to facebook";
Request request = Request
.newStatusUpdateRequest(Session.getActiveSession(), message, place, tags, new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(message, response.getGraphObject(), response.getError());
}
});
request.executeAsync();
} else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}

Related

Facebook Checkin from Android App

I am trying to perform a Facebook Checkin from an Android app that I am developing. I know we have to use the graph API. But I am not sure what all are required to get it working. Is there an example code for this?
I reviewed this link: Publishing checkins on facebook through android app
How do I use this code? Any help on this is appreciated.
public class FBCheckin extends Fragment implements View.OnClickListener {
Button checkin;
public String pageID;
String FACEBOOK_LINK = "https://www.facebook.com/pizzaguydelivery";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
final View rootview = inflater.inflate(R.layout.fblogin, container, false);
checkin.setOnClickListener(this);
return rootview;
}
#Override
public void onClick(View v) {
LoginManager.getInstance().logInWithPublishPermissions(getActivity(), Arrays.asList("publish_actions"));
pageID = FACEBOOK_LINK.substring(FACEBOOK_LINK.lastIndexOf("/") + 1, FACEBOOK_LINK.length());
new GraphRequest(AccessToken.getCurrentAccessToken(), "/" + pageID, null, HttpMethod.GET, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
try {
if (response.getError() == null) {
JSONObject obj = response.getJSONObject();
if (obj.has("id")) {
pageID = obj.getString("id");
Bundle params = new Bundle();
params.putString("message", "Eating");
params.putString("place", pageID);
// params.putString("link", "URL");
if (pageID == null) {
//Toast.makeText(getApplicationContext(),"Failed to check in",Toast.LENGTH_SHORT).show();
} else {
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/feed", params, HttpMethod.POST, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
if (response.getError() == null) {
//success
} else {
//Toast.makeText(getApplicationContext(),"Failed to check in",Toast.LENGTH_SHORT).show();
}
}
}).executeAsync();
}
}
}
} catch (JSONException q) {
// TODO Auto-generated catch block
//Toast.makeText(getApplicationContext(),q.getMessage(),Toast.LENGTH_SHORT).show();
q.printStackTrace();
}
}
}).executeAsync();
}
}
The following code only checks in to locations with facebook pages via pageid. ( Like restaurants.) But think you can do it with place id too.
LoginManager.getInstance().logInWithPublishPermissions(
getActivity(), Arrays.asList("publish_actions"));
String PAGEID = FACEBOOK_LINK.substring(
FACEBOOK_LINK.lastIndexOf("/") + 1,
FACEBOOK_LINK.length());
new GraphRequest(AccessToken.getCurrentAccessToken(), "/"
+ PAGEID, null, HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
try {
if (response.getError() == null) {
JSONObject obj = response
.getJSONObject();
if (obj.has("id")) {
pageID = obj.getString("id");
/* make the API call */
Bundle params = new Bundle();
params.putString("message", "Eating");
params.putString("place", pageID);
params.putString("link","URL");
if (pageID == null) {
MessageBox
.Show(getActivity(),
"Failed to check in to this restaurant");
} else {
new GraphRequest(AccessToken
.getCurrentAccessToken(),
"/me/feed", params,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(
GraphResponse response) {
if (response.getError() == null) {
//success
} else {
MessageBox
.Show(getActivity(),
"Failed to check in to this restaurant");
}
}
}).executeAsync();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
MessageBox.Show(getActivity(),
"Error: " + e.getMessage());
e.printStackTrace();
}
}
}
}).executeAsync();
I know this code is a bit messy but it get the work done. Here the first thing that I am doing is asking user for facebook publish permission. Then I check if the pageID that I am checking into is valid through a graph request. If it is valid then I am checking in the user to his desired location through another request.

Facebook Graph API /me Request

I am attempting to incorporate a Facebook login into my Android Application. The issue that I am having is that I cannot seem to make a successful /me request request with extra parameters.
If I attempt to do a /me request on its own, than I can get the User ID, and Name. I want to get extra fields, such as email, first_name, last_name, etc.
ERROR
{Response: responseCode: 400, graphObject: null, error: {HttpStatus:
400, errorCode: 2500, errorType: OAuthException, errorMessage: An
active access token must be used to query information about the
current user.}}
TRYING TO MAKE REQUEST
I do this from within the onSuccess method inside a LoginManager.
new GraphRequest(
loginResult.getAccessToken(),
"/me?fields=id,name,email",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
}
}
).executeAsync();
I think something is wrong at loginResult.getAccessToken(), try this:
Bundle params = new Bundle();
params.putString("fields", "id,name,email");
new GraphRequest(
AccessToken.getCurrentAccessToken(), //loginResult.getAccessToken(),
"/me",
params,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
try {
Log.e("JSON",response.toString());
JSONObject data = response.getJSONObject();
//data.getString("id"),
//data.getString("name"),
//data.getString("email")
} catch (Exception e){
e.printStackTrace();
}
}
}
).executeAsync();
Check login success with full Permission you want
if (AccessToken.getCurrentAccessToken().getDeclinedPermissions().size() == 0) {
}
I can try to help you out since I just went through the facebook log in and pull back name and email but we really need to see all your code. I'd post all that you can that has anything to do with how you are using facebook classes. Here are parts of what I used if it helps at all:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
loginButtonFacebook = (LoginButton) findViewById(R.id.login_button_facebook);
loginButtonFacebook.setReadPermissions("user_friends,email");
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
accessToken = loginResult.getAccessToken();
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("facebookAccessToken", accessToken.getToken()).apply();
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
getFacebookItems(object);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,first_name,last_name,email,picture");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.d(TAG, "Canceled");
}
#Override
public void onError(FacebookException exception) {
Log.d(TAG, String.format("Error: %s", exception.toString()));
}
});
}
....
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
public void getFacebookItems(JSONObject object){
try {
facebookId = object.getString("id");
facebookName = object.getString("name");
facebookFirstName = object.getString("first_name");
facebookLastName = object.getString("last_name");
facebookEmail = object.getString("email");
}catch (JSONException e) {
e.printStackTrace();
}
}
I also access facebook user friends from another activity so I store my accesstoken in preferences for when I need it later.
accessTokenString = prefs.getString("facebookAccessToken", "");
String facebookId = prefs.getString("facebookId", "");
if (facebookId.length() > 0 && accessTokenString.length() > 0) {
accessToken = new AccessToken(accessTokenString, getString(R.string.facebook_app_id), facebookId, null, null, null, null, null);
storeFacebookFriends();
}
....
public void storeFacebookFriends(){
if (accessToken != null) {
GraphRequestBatch batch = new GraphRequestBatch(
GraphRequest.newMyFriendsRequest(
accessToken,
new GraphRequest.GraphJSONArrayCallback() {
#Override
public void onCompleted(JSONArray jsonArray, GraphResponse response) {
// Application code for users friends
userArray = jsonArray;
}
})
);
batch.addCallback(new GraphRequestBatch.Callback() {
#Override
public void onBatchCompleted(GraphRequestBatch graphRequests) {
// Application code for when the batch finishes
}
});
batch.executeAsync();
}
}

Android - How to update Status on Facebook attaching a picture

I'm using the Facebook's SDK for Android. I'm using the newStatusUpdateRequest() method to update my Status with a simple message, it works fine. But I don't find the way to attach a picture or an URL to the post.
private void postStatusUpdate() {
if (canPresentShareDialog) {
FacebookDialog shareDialog = createShareDialogBuilderForLink().build();
uiHelper.trackPendingDialogCall(shareDialog.present());
} else if (user != null && hasPublishPermission()) {
final String message = getString(R.string.status_update, user.getFirstName(), (new Date().toString()));
Request request = Request
.newStatusUpdateRequest(Session.getActiveSession(), message, place, tags, new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(message, response.getGraphObject(), response.getError());
}
});
request.executeAsync();
} else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}
I was reading also this link, with all the facebook API methods, but I can't find the way to post both in my Status: a message and a picture:
https://developers.facebook.com/docs/reference/android/3.0/class/Request/#newStatusUpdateRequest
Has anyone solved already a similar problem?
Update. I think to post a picture I should use the method:
public static Request newGraphPathRequest(Session session, String graphPath, Callback callback)
Where graphPath should be the link to the picture. But I don't know how to join both, message and picture in the same Request.
Thanks you very much for your time
Ok I solved it:
private void postStatusUpdate() {
if (canPresentShareDialog) {
FacebookDialog shareDialog = createShareDialogBuilderForLink().build();
uiHelper.trackPendingDialogCall(shareDialog.present());
} else if (user != null && hasPublishPermission()) {
Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.icon);
Request request = Request.newUploadPhotoRequest(Session.getActiveSession(), image, new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(getString(R.string.photo_post), response.getGraphObject(), response.getError());
}
});
final String message = getString(R.string.status_update, user.getFirstName(), (new Date().toString()));
Bundle params = request.getParameters();
params.putString("message", message);
request.executeAsync();
} else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}
If anyone has got a better solution, feel free to comment

android: how to post status on facebook

I want to update status of user along with location of user in android. I have latitude, longitude and name of the location.
I have already updated status but couldn't figure out how to post it along with location.
Session session = Session.getActiveSession();
Request.Callback callback = new Request.Callback() {
#Override
public void onCompleted(Response response) {
Log.d("Checkin", response.toString());
Toast.makeText(context, response.toString(),
Toast.LENGTH_LONG).show();
}
};
if (session != null && session.isOpened()) {
Request.newStatusUpdateRequest(session,
"Posting from my fyp", null, null, callback)
.executeAsync();
}
we can do this using latest Facebook SDK:
Location location = new Location("provider");
location.setLatitude(13.1234);
location.setLongitude(13.1234);
final Session session = Session.getActiveSession();
Request placesSearchRequest = Request.newPlacesSearchRequest(session, location, 100,
1, "",
new GraphPlaceListCallback() {
#Override
public void onCompleted(List<GraphPlace> places, Response response) {
Request statusUpdateRequest = Request.newStatusUpdateRequest(session, "Hell Yea :P #fyp #success #viaCheckinApp",
places.get(0), null, new Callback() {
#Override
public void onCompleted(Response response) {
debug("response of posting checkin to facebook: " + response.toString());
}
});
statusUpdateRequest.executeAsync();
}
});
placesSearchRequest.executeAsync();

Post on FB wall Using 3.0 SDK

Hello fellow programmers, I having difficulties on the new Facebook SDK,
Scenario is:
im using fragment so I follow this steps
Why doesn't Android Facebook interface work with Fragments?
and now Im getting the oncomplete and the token ID
Now I want to post on my wall so ive created this function
private void publishStory(Session session) {
if (session != null){
// Check for publish permissions
session.addCallback(new StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
List<String> PERMISSIONS = Arrays
.asList("publish_actions");
session
.requestNewPublishPermissions(new Session.NewPermissionsRequest(
getActivity(), PERMISSIONS));
Request request = Request.newStatusUpdateRequest(
session, "Temple Hello Word Sample",
new Request.Callback() {
#Override
public void onCompleted(Response response) {
Log.i("fb:done = ", response.getGraphObject() + ","
+ response.getError());
}
});
request.executeAsync();
}
});
And put the Declaration on the Oncomplete
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
publishStory(session);
}
else
{
Log.v("FACEBOOK ", "NO ACCESS");
}
}
});
}
My problem is on this line of code session.addCallback(new StatusCallback() { it skips the next step thus ending the function without posting on my wall.
I am quite sure that the session is active as I have applicationID and access token..
Any Help?
Thanks
EDIT
Im using this code based on the Answer below and added new permissions
private void publishStoryTEST(final Session session)
{
if (session != null)
{
Bundle postParams = new Bundle();
postParams.putString("message", "TEST");
Request.Callback callback = new Request.Callback()
{
public void onCompleted(Response response)
{
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try
{
postId = graphResponse.getString("id");
}
catch (JSONException e)
{
Log.i("JSON", "JSON error " + e.getMessage());
}
FacebookRequestError error = response.getError();
Log.e("post response", response.toString());
if (error != null)
{
}
else
{
}
}
};
List<String> PERMISSIONS = Arrays
.asList("publish_actions");
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(getActivity(), PERMISSIONS));
Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
But still Im getting an error saying
The user hasn't authorized the application to perform this action
Why is that I still get that error? Does the permission never called?
The problem is common, i am sharing with you the working source code of the Posting Method that i am currently using in my Application.
private void publishStory(String status)
{
Session session = Session.getActiveSession();
if (session != null)
{
Bundle postParams = new Bundle();
postParams.putString("message", status);
Request.Callback callback = new Request.Callback()
{
public void onMalformedURLException(MalformedURLException e)
{
}
public void onIOException(IOException e)
{
}
public void onFileNotFoundException(FileNotFoundExceptione)
{
}
public void onFacebookError(FacebookError e)
{
}
public void onCompleted(Response response)
{
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try
{
postId = graphResponse.getString("id");
}
catch (JSONException e)
{
Log.i("JSON", "JSON error " + e.getMessage());
}
FacebookRequestError error = response.getError();
Log.e("post response", response.toString());
if (error != null)
{
}
else
{
}
}
};
Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
I hope this solves your problem.
EDIT:
Please refer to the following links, for a detailed procedure of setting up Facebook SDK 3.0 with proper permissions and posting features.
Post to facebook after login fails Android
http://www.kpbird.com/2013/03/android-login-using-facebook-sdk-30.html
// Try below code
private void postData() {
lnrPbr.setVisibility(View.VISIBLE);
isSharingData = true;
Session session = Session.getActiveSession();
if (session != null) {
Bundle postParams = new Bundle();
postParams.putString("name", getIntent().getStringExtra("IN_SHARE_CAPTION") == null ? "" : getIntent().getStringExtra("IN_SHARE_CAPTION"));
postParams.putString("caption", getIntent().getStringExtra("IN_SHARE_CAPTION") == null ? "" : getIntent().getStringExtra("IN_SHARE_CAPTION"));
postParams.putString("description", getIntent().getStringExtra("IN_SHARE_DESCRIPTION") == null ? "" : getIntent().getStringExtra("IN_SHARE_DESCRIPTION"));
postParams.putString("link", getIntent().getStringExtra("IN_SHARE_SHARELINK") == null ? "" : getIntent().getStringExtra("IN_SHARE_SHARELINK"));
postParams.putString("picture", getIntent().getStringExtra("IN_SHARE_THUMB") == null ? "" : getIntent().getStringExtra("IN_SHARE_THUMB"));
postParams.putString("message", getIntent().getStringExtra("IN_SHARE_MESSAGE") == null ? "" : getIntent().getStringExtra("IN_SHARE_MESSAGE"));
Request.Callback callback = new Request.Callback() {
public void onCompleted(Response response) {
isSharingData = false;
lnrPbr.setVisibility(View.GONE);
FacebookRequestError error = response.getError();
if (error != null) {
IjoomerUtilities.getCustomOkDialog(getString(R.string.facebook_share_title), error.getErrorMessage(), getString(R.string.ok), R.layout.ijoomer_ok_dialog, new CustomAlertNeutral() {
#Override
public void NeutralMethod() {
finish();
}
});
} else {
IjoomerUtilities.getCustomOkDialog(getString(R.string.facebook_share_title), getString(R.string.facebook_share_success), getString(R.string.ok), R.layout.ijoomer_ok_dialog, new CustomAlertNeutral() {
#Override
public void NeutralMethod() {
finish();
}
});
}
}
};
Request request = new Request(Session.getActiveSession(), "me/feed", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
Refer this tutorial..
http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}

Categories

Resources