Android - How to post a comment using Facebook SDK 4.0.1 - android

Is there any way to post a comment using FacebookSDK 4.0.1.
Because Request was removed in new SDK.
Assume that I had login and got "publish_actions" permission.
private void facebookLogin() {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("user_friends"));
}
private void facebookLogout (){
LoginManager.getInstance().logOut();
}
private void facebookPost() {
//check login
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken == null) {
Log.d(TAG, ">>>" + "Signed Out");
status = Status.POST;
facebookLogin();
return;
} else {
Log.d(TAG, ">>>" + "Signed In");
status = Status.NONE;
}
if (accessToken.getPermissions().contains("publish_actions")) {
Log.d(TAG, ">>>" + "contain publish_actions");
//I wanna post a comment in here
} else {
Log.d(TAG, ">>>" + "NOT contain publish_actions");
LoginManager.getInstance().logInWithPublishPermissions(this, Arrays.asList("publish_actions"));
}
}

Have you tried sharing using com.facebook.share.widget.ShareApi class
ShareApi.share(content,null);

Assuming that you want to post something on a users wall, here are the steps you need to take in order to use Facebook Post, using Open Graph Stories
1) Head on to the Developer Console
2) Register your application, create the new login flow - be warned the older login flow does not work with SDK 4.0
3) Now once login is working for you, Head on to the Dashboard for this app, select Open Graph from the pane on left.
4) Define your Actions, Stories and Objects here.
5) Although Facebook has given an option to get code, next to the Stories, Action Types and Object Types - be warned this code is old and will not work.
Here is what works for me:
My app name is (as defined on the Dev Console)
friendssampleapp
My Action Type: Celebrating
My Object Type: Milestone
Here is the snippet of code I use to post via a button click:
ShareOpenGraphObject object = new ShareOpenGraphObject.Builder()
.putString("og:type", "friendsampleapp:milestone")
.putString("og:title", "A Game of Thrones")
.putString("og:description", "In the frozen wastes to the north of Winterfell, sinister and supernatural forces are mustering.")
// .putPhoto("og:image", photo)
.build();
// Create an action
ShareOpenGraphAction action = new ShareOpenGraphAction.Builder()
.setActionType("friendsampleapp:celebrating")
.putObject("milestone", object)
.build();
// Create the content
ShareOpenGraphContent content = new ShareOpenGraphContent.Builder()
.setPreviewPropertyName("milestone")
.setAction(action)
.build();
ShareDialog.show(getActivity(), content);

use below code:
Bundle params = new Bundle();
params.putString("message", "This is a test message");
new GraphRequest(
accessToken,
"/me/feed",
params,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
}
}
).executeAndWait();

Related

Facebook Graph Api Android sharing image on a page

I want to share an image on a Facebook page of mine. But I couldn't figure out how to do this step by step. And couldn't find step by step guide for this.
This is my code to share an image on a page
Bundle params = new Bundle();
String nameText = name.getText().toString();
String tags = engine.implodeTags(tagsList);
String textText = text.getText().toString();
params.putString("caption", nameText + "\n\n" + textText + "\n\n" + tags);
params.putString("url", imagesList.get(mainImageSelected).getImageUrl());
params.putString("access_token", "{access token here}");
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/{page_id here}/photos",
params,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
if(response.getJSONObject()!=null) {
Log.d("qwe", response.getJSONObject().toString());
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, "Shared on facebook", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
});
}
else{
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, "Error", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
});
}
}
}
).executeAsync();
It works if I put access token by hand. I am getting access token here
https://developers.facebook.com/tools/explorer .
But after some time this access token is not working any more. So I need to get new access token.
How to get PAGE access token from android itself? Via user login button of facebook sdk?
https://developers.facebook.com/docs/facebook-login/access-tokens
Please help.
Easily if you use facebook SDK to do that. read at here https://developers.facebook.com/docs/sharing/android
You need to get Permanent access token to share images on your Page. To get that you need to follow steps written here.
facebook: permanent Page Access Token?

Unable to post open graph custom story with new Facebook sdk 4.1

Im trying to use the Facebook new ShareApi to post a custom story but i can't make it work i don't know what im doing wrong.
The custom story works fine its been approved by Facebook and im currently using it in my iOS app.
First i create the object:
ShareOpenGraphObject object = new ShareOpenGraphObject.Builder()
.putString("og:type","clinpays:site")
.putString("og:title","MY_TITLE")
.putString("og:description","MY_DESCRIPTION!")
.putString("og:url",MY_URL)
.build();
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bizBitmap)
.setUserGenerated(true)
.build();
Then i create the action:
ShareOpenGraphAction action = new ShareOpenGraphAction.Builder()
.setActionType("clinpays:checkin")
.putObject("clinpays:site", object)
.putPhoto("photo", photo)
.build();
Create the content:
ShareOpenGraphContent content = new ShareOpenGraphContent.Builder()
.setPreviewPropertyName("clinpays:site")
.setAction(action)
.build();
and use the shareapi:
ShareApi.share(content,new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
Log.d(Check.TAG, "Story posted! " + result);
}
#Override
public void onCancel() {
Log.d(Check.TAG, "canceled");
}
#Override
public void onError(FacebookException e) {
Log.d(Check.TAG, "error posting: "+e.getMessage() );
}
});
all i get in the console is:
error posting: Invalid parameter
You need to remove the name space from setPreviewPropertyName("clinpays:site") to be setPreviewPropertyName("site"), and remove the name space from putObject of the action as well.

Facebook request in Android - profile picture is not available anymore

In an Android App I have the following code:
private void requestDataFromFb() {
Callback callback = new Callback() {
#Override
public void onCompleted(Response response) {
AppLog.Log(TAG, "Facebook Response ::" + response + "");
Utility.closeprocess(Login.this);
loadImage(response);
}
};
String graphPath = "me";
Bundle bundle = new Bundle();
bundle.putString("fields",
"id,picture.height(250),gender,first_name,last_name,age_range");
Request mRequest = new Request(Session.getActiveSession(), graphPath,
bundle, HttpMethod.GET, callback);
RequestAsyncTask task = Request.executeBatchAsync(mRequest);
if (task == null) {
AppLog.Log(TAG, "task is null");
} else {
AppLog.Log(TAG, task.getStatus() + "");
}
}
It's been working fine and I am getting the paths to the user's profile picture. However, after some time the paths don't work anymore. One cannot see the picture of the first users. When I enter the URL in my browser I get:
An error occurred while processing your request.
Reference #50.3d1431b5.1424197137.a584ec67
And when using the Graph API Explorer of Facebook I get a different URL for the picture.
I do not know if that has something to do with the fact that the user has changed their profile picture or something else, and how I could solve this issue.
Any advise or guidance would be greatly appreciated

facebook sdk: share local picture with text is driving me crazy

GOAL
In my camera app i want to let user share a picture with pre-formatted text and a description on the user's facebook wall.
INTRO
I Googled a lot and followed "the terrific" facebook-getting-started, trying many things, for !!days!!... no completely working solutions found yet.
At least i think i got some points:
The great Android Intent action_send works great but not choosing facebook, that works for text OR for pictures, not for both (!!), see here
applicationID, hashxxx, and everything else needed to link android app to facebook login, all things that i really don't understand and don't want to, done and at last working (thanx facebook for all this sh*t!!)
share with facebook can be done (see here):
3a. using the facebook app (installed in the device)
3b. using a login session (if facebook app is not installed)
Facebook wants us to use its SDK, it's very [b|s]ad, but i can stand it.
case 3a - facebook suggests us to use the shareDialog, and -fighting a lot with code snippets and samples suggested!- i have been able to do it, but i need it to work also if facebook app is not installed (case 3b.)
case 3b - facebook suggests to use the "ugly" feedDialog as a fallback (see here).
6a. feedDialog needs login and it's ok...
6b. it seems feedDialog cannot share local images, i really don't understand why... here facebook guide talks only about "URL" for the "picture" keyword...
5c. then i think i must use Request, i tried implementing it but nothing happened, i think i'm missing something... No useful references (=working examples) found.
CODE SNIPPETS copy/paste/edit from SO and developers.facebook
ShareDialog and session management in case facebook app is not installed IT'S WORKING
/**
* share image with facebook, using facebook sdk
* #param pathToImage
*/
private void shareWithFacebook(String pathToImage) {
Log.i("SHARE", "share with facebook");
if (FacebookDialog.canPresentShareDialog(getApplicationContext(), FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) {
// Publish the post using the Share Dialog
Log.i("SHARE", "share with ShareDialog");
FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(this)
.setCaption("Sharing photo taken with MyApp.")
.setName("Snail Camera Photo")
.setPicture("file://"+pathToImage)
.setLink("http://myapplink")
.setDescription("Image taken with MyApp for Android")
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
} else {
// maybe no facebook app installed, trying an alternative
// here i think i need a session
if (Session.getActiveSession() != null && Session.getActiveSession().isOpened()) {
publishFeedDialog(pathToImage);
} else {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
List<String> permissions = new ArrayList<String>();
permissions.add("publish_actions");
session.openForRead(new Session.OpenRequest(this)
.setPermissions(permissions)
.setCallback(mFacebookCallback));
} else {
Session.openActiveSession(this, true, mFacebookCallback);
}
}
}
}
private Session.StatusCallback mFacebookCallback = new Session.StatusCallback() {
public void call(final Session session, final SessionState state, final Exception exception) {
if (state.isOpened()) {
String facebookToken = session.getAccessToken();
Log.i("SHARE", facebookToken);
Request.newMeRequest(session, new Request.GraphUserCallback() {
public void onCompleted(GraphUser user, com.facebook.Response response) {
publishFeedDialog(MP.LAST_TAKEN_FOR_GALLERY);
}
}).executeAsync();
}
}
};
feedDialog snippet, works for text fields, links, and remote url, but DOESN'T WORK FOR LOCAL PICTURES using "file://..." nor "file:///...". Error message: picture URL is not properly formatted.
private void publishFeedDialog(String pathToImage) {
Bundle params = new Bundle();
params.putString("name", "myapp Photo");
params.putString("caption", "Sharing photo taken with myapp.");
params.putString("description", "Image taken with myapp for Android");
params.putString("link", "http://myapp.at.playstore");
params.putString("picture", "file://"+pathToImage);
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(EnhancedCameraPreviewActivity.this,//getApplicationContext(),
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
public void onComplete(Bundle values,
FacebookException error) {
Log.i("SHARE", "feedDialog.onComplete");
if (error == null) {
// story is posted
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(getApplicationContext(),
"Posted story, id: "+postId,
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(getApplicationContext(),
"Error posting story",
Toast.LENGTH_SHORT).show();
}
}
})
.build();
feedDialog.show();
}
Another try, using Request, it says:
photo upload problem. Error={HttpStatus: 403, errorCode: 200,
errorType: OAuthException, errorMessage: (#200) Requires extended
permission: publish_actions}
I tried adding publish_actions permission in the session management above, maybe i miss something...
private void publishFeedDialog(String pathToImage) {
Request request=Request.newPostOpenGraphObjectRequest(
Session.getActiveSession(),
"PhotoUpload",
"myApp Photo Upload",
"file://"+pathToImage,
"http://myapp.at.playstore",
"Image taken with myApp for Android",
null,
uploadPhotoRequestCallback);
request.executeAsync();
}
Last try with Request, absolutely nothing happens, both with or without "picture" keyword.
private void publishFeedDialog(String pathToImage) {
Bundle parameters = new Bundle();
parameters.putString("message", "Image taken with myApp for Android");
parameters.putString("picture", "file://"+pathToImage);
parameters.putString("caption", "myApp Photo");
Request request = new Request(Session.getActiveSession(), "/me/feed", parameters, null);
// also tried: Request request = new Request(Session.getActiveSession(), "/me/feed", parameters, com.facebook.HttpMethod.POST);
request.executeAsync();
}
QUESTIONS
-1- Are there some faults in my 1..6 points?
-2- Can i share a local picture using FeedDialog?
-3- if not, how to when facebook app is not installed?
Thanks a lot!
I have the same problem, but I have a workaround.
I can't find any wrong reasoning in your point 1-6, look like the same issues I've come acrossed.
You can't share pictures locally, but...
Code snippet below:
This will upload the picture to the users profile and post it on his\hers wall, afterwhich you can get the URL if needed:
private void uploadPicture(final String message, Session session) {
Request.Callback uploadPhotoRequestCallback = new Request.Callback() {
#Override
public void onCompleted(com.facebook.Response response) {
if (response.getError() != null) {
Toast.makeText(getActivity(), "Failed posting on the Wall", Toast.LENGTH_LONG).show();
return;
}
Object graphResponse = response.getGraphObject().getProperty("id");
if (graphResponse == null || !(graphResponse instanceof String) ||
TextUtils.isEmpty((String) graphResponse)) {
Toast.makeText(getActivity(), "Failed uploading the photo\no respons", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Succsefully posted on the facebook Wall", Toast.LENGTH_LONG).show();
}
}
};
// Execute the request with the image and appropriate message
Request request = Request.newUploadPhotoRequest(session, profileBitmap, uploadPhotoRequestCallback);
Bundle params = request.getParameters();
params.putString("message", message);
request.executeAsync();
}
And to start facebook login when you don't have the APP, it's simpler, I use the following code snippet for calling the facebook SDK on facebook button:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.faceBookButton:
if (((imagePath != null && !imagePath.equals("")) || (message != null && !message.equals("")))) {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForPublish(new Session.OpenRequest(this)
.setPermissions(Arrays.asList("public_profile", "publish_actions"))
.setCallback(statusCallback));
} else {
if (profileBitmap != null) {
uploadPicture(message, session);
} else {
publishFeedDialog(message);
}
}
} else {
Toast.makeText(getActivity(), getString(R.string.checkin_fail), Toast.LENGTH_SHORT).show();
}
break;
}
}
In my case publishFeedDialog accepts the message you want to pass on, and not the image, but it doesn't matter. It opens up Facebook's message dialog anyway to which I haven't yet found a way to pass a predefined message from my EditText widget.

Android Facebook-sdf Exception: Failed to generate preview for user

i'm developing a simple android app and i want post a status in facebook using OpenGraphObject and OpenGraphAction.
if i use new FacebookDialog.ShareDialogBuilder(this) i have no problem, but when i'm using FacebookDialog.OpenGraphActionDialogBuilder i got the error:
01-09 15:56:29.594 11439-11439/simov.project2.yourcity E/Activity﹕ Error: com.facebook.FacebookException: Failed to generate preview for user.
java
public void test(int position){
File f = (File)mImageAdapter.getItem(position);
Bitmap myBitmap= BitmapFactory.decodeFile(f.getAbsolutePath());
List<Bitmap> images = new ArrayList<Bitmap>();
images.add(myBitmap);
//Session session = Session.getActiveSession();
//session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSION));
try {
addresses = mGeocoder.getFromLocation(mItenerariumState.getCurrentLocation().getLatitude()
, mItenerariumState.getCurrentLocation().getLongitude()
, 1);
} catch (IOException e) {
e.printStackTrace();
}
OpenGraphObject location = OpenGraphObject.Factory.createForPost("yourcity:location");
if(!addresses.isEmpty()){
location.setProperty("title", addresses.get(0).getAddressLine(0));
} else {
location.setProperty("title", "Unknown place");
}
location.setProperty("Description", "I visited this place using YourCity App");
OpenGraphAction action = GraphObject.Factory.create(OpenGraphAction.class);
action.setProperty("location", location);
/* Request request = Request.newPostOpenGraphActionRequest(Session.getActiveSession(), action, new Request.Callback() {
#Override
public void onCompleted(Response response) {
//showPublishResult(getString(R.string.photo_post), response.getGraphObject(), response.getError());
}
});
request.executeAsync();*/
FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(this, action, "yourcity:visit","location")
.setApplicationName("YourCity")
//.setImageAttachmentsForAction(images, true)
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
}
Important note, the shareDialog show in the screen by like one second and then disappears without any action
Have been dealing with this error for hours.
Heres how I fixed it.
The Actions and Objects you specified in your code are the ones that cause the problem.
The samples provided on the Facebook developers guide aren't good enough I feel.
Heres a sample code you can use that will work perfectly.
Basically make sure your ObjectType -> eg: video.other is set correctly and your Action type e.g: video.watches is set right.
void sometestCode(){
OpenGraphObject video = OpenGraphObject.Factory.createForPost("video.other");
video.setTitle("Awesome Video");
video.setDescription("This video will show you how to make the Opengraph work");
OpenGraphAction action = GraphObject.Factory.create(OpenGraphAction.class);
action.setProperty("video", video);
action.setType("video.watches");
FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(this, action, "video")
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
}
We had the exact same error some times ago.
Check you are using the correct action type in OpenGraphActionDialogBuilder.
We fixed the same error just using the correct action type parameter.
In your case you should check if "yourcity:visit" is the name of the action.
Go to developer consolle
https://developers.facebook.com/x/apps/your-app-id/open-graph/action-types/ and click on Get Code for the action you want to implement. Then read the url that should looks like something like this:
https://graph.facebook.com/me/app_namespace:app_action?...
then use the correct app_action in your code. It should fix!

Categories

Resources