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!
Related
I have been exploring the Facebook documentations but still yet to find on how to Check-in or share place. Most answers were already deprecated and I need to implement using the updated Facebook SDK. Did I miss something in the Documentations? Or do I have to use third party applications??? Besides the primary way of Sharing using the SDK, I also know how to use ACTION_SEND on sharing media content on facebook, is it possible to insert a place parameter there?
If you are using facebook share button it'll be like this
ShareContent sharecontent = new ShareLinkContent.Builder()
.setPlaceId("141887372509674")
.build();
btnfacebookshare.setShareContent(sharecontent);
Put a placeID on ShareContents
There are also ShareContent subclasses you may use with setPlaceId() like SharePhotoContent, ShareVideoContent, and ShareOpenGraphContent.
It is not clearly stated on the documentations (https://developers.facebook.com/docs/reference/android/current/class/ShareLinkContent/) but with experimentations I came up with it
The placeId needs to be requested using GraphRequest which can be done using:
String facebookUrl = "https://www.facebook.com/mybusiness";
final String PAGE_ID_FROM_URL = facebookUrl.substring(facebookUrl.lastIndexOf("/") + 1, facebookUrl.length());//now PAGE_ID_FROM_URL = mybusiness
//request for page id
new GraphRequest(AccessToken.getCurrentAccessToken(), "/"+ PAGE_ID_FROM_URL , null, HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
JSONObject obj = response.getJSONObject();
if (obj.has("id")) {
try {
String pageID = obj.getString("id");
ShareDialog share = new ShareDialog(MyActivity.this);
ShareContent shareContent = new ShareLinkContent.Builder().setPlaceId(pageID).setPageId(pageID).build();
share.show(shareContent, ShareDialog.Mode.AUTOMATIC);
} catch (JSONException e) {
e.printStackTrace();
}
}
}).executeAsync();
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();
I'm trying to share a link(my Google Play app link) using ShareDialog from Facebook SDK but the problem is that when the URL is my app's Google Play link the other information is not displayed correctly... Actually it's displaying only the link from Google Play without name or description!
Here's the code:
FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(
this)
.setLink("https://play.google.com/store/apps/details?id=<myapp>")
.setDescription("Test")
.setName("Test for facebook")
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
I tried everything and with other URL's actually is working(displaying name, description, caption etc.) but not with the app's URL.
Does anyone know why a Google Play link won't work with text, description or caption?
Actually if you specify the contentUrl (as in 4.0) or link (as in your case), it overrides the name, description, etc. You just don't need to give other things as it then becomes responsibility of url host to supply the details that should be shown when it gets posted on Facebook timeline.
Although, if you want to share something like Message from user followed by your app link. Then I would suggest to go for Graph API (I wasted 2-3 days in posting something like this via ShareApi/ShareDialog but ended up with using Graph API only.)
Code to share using Graph API:
// Constants to be used when sharing message on facebook time line.
private static final int FACEBOOK_ERROR_PERMISSION = 200;
private static final String PARAM_EXPLICIT = "fb:explicitly_shared";
private static final String PARAM_GRAPH_PATH = "/me/feed";
private static final String PARAM_MSG = "message";
private static final String PARAM_LINK = "link";
// Create the parameter for share.
final Bundle params = new Bundle();
params.putBoolean(PARAM_EXPLICIT, true);
params.putString(PARAM_LINK, BirdingUtah.APP_URL);
// If message is empty, only our link gets posted.
String message = "This is the message to share";
if (!TextUtils.isEmpty(message))
params.putString(PARAM_MSG, message);
// Send the request via Graph API of facebook to post message on time line.
new GraphRequest(AccessToken.getCurrentAccessToken(), PARAM_GRAPH_PATH,
params, HttpMethod.POST, new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse graphResponse) {
searchDialog.dismiss();
if (graphResponse.getError() == null) {
// Success in posting on time line.
Logger.toastShort(R.string.msg_share_success);
Logger.debug(TAG, "Success: " + graphResponse);
} else {
FacebookRequestError error = graphResponse.getError();
if (error.getErrorCode() == FACEBOOK_ERROR_PERMISSION)
// Cancelled while asking permission, show msg
Logger.toastLong(R.string.msg_share_permission);
else
// Error occurred while posting message.
Logger.toastShort(R.string.msg_share_error);
Logger.error(TAG, "Error: " + error);
}
// Enable the button back again if profile and access token are non null.
if (Profile.getCurrentProfile() != null || AccessToken.getCurrentAccessToken() != null)
mShareButton.setEnabled(true);
}
}).executeAsync();
I'm creating an android camera app and I would like to connect it to Facebook.
I created a page for my app and created an Open Graph story "x took a Photo using MyApp".
I'm using a the OpenGraphActionDialogBuilder but for some reason I havnt been able to see the preview of the attached image in the OpenGraphActionDialog which is created.
here is my code:
public void shareWithFacebook(File imageFile) {
// get session
Session session = Session.getActiveSession();
// make sure we have publish permissions
boolean hasPublishPermissions = hasPublishPermission();
if (!hasPublishPermissions) {
if (!session.isOpened()) {
Session.OpenRequest openRequest = new Session.OpenRequest(this);
openRequest.setPermissions("user_friends");
session.openForRead(openRequest);
}
requestPublishPermissions(session);
}
ArrayList<File> files = new ArrayList<File>();
files.add(imageFile);
OpenGraphAction action = OpenGraphAction.Factory.createForPost("mycameraapp:took");
OpenGraphObject picture = OpenGraphObject.Factory.createForPost("mycameraapp:picture");
picture.setProperty("title", "");
action.setProperty("picture", picture);
FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(this, action, "picture" )
.setImageAttachmentFilesForObject("picture", files, true)
.build();
if (FacebookDialog.canPresentOpenGraphActionDialog(this))
shareDialog.present();
}
You need to add:
action.setProperty("previewPropertyName", picture);
I have an app on Facebook (we'll call it mygame), connected with an Android game I'm developing.
In this mobile app, I want to let users to share their scores after a match. For this, I've considered the use of Open Graph stories, actions and objects.
The first thing I've done is to create an action, "Play" and an object "Match", this one with an integer property named "score".
After that, I've created my first story in the form "Play a Match" using the relative button "Add custom story".
First problem: all the generated examples don't show a preview, instead a red message appears, Unable to Generate Story.
This problem was previously treated on Stackoverflow, and the cause was related to the fact that "facebook has no examples of the story to render".
That should not be true in my case, because if I open the Object Browser I can see two auto-generated Match objects. Does Facebook try to generate example stories from those records?
If not (or even true), what's the problem?
Second problem SOLVED, SEE ANSWERS: on Android, simply, I can't test this story due to an exception that says com.facebook.FacebookException: Failed to generate preview for user..
The method I've used to show a Facebook Dialog with the details of this "played match" is the one described here: https://developers.facebook.com/docs/android/open-graph#sharedialog-setup
In my app, the code is the following:
OpenGraphObject setObj = OpenGraphObject.Factory.createForPost("mygame:match");
setObj.setProperty("score", set.getThisUserScore());
setObj.setProperty("title", set.getType().getDisplayString());
setObj.setProperty("url", "http://www.mygame.com");
setObj.setProperty("description", "Can you beat me?");
OpenGraphAction action = GraphObject.Factory.create(OpenGraphAction.class);
action.setType("mygame:play");
action.setProperty("match", setObj);
FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(activity, action, "match").build();
activity.getUiHelper().trackPendingDialogCall(shareDialog.present());
Once called, the Dialog appears on my device, but it closes itself after one second, throwing the exception.
I really can't focus on where the problem is (I'm trying to implement the simplest way of sharing stories). Are these two problems connected?
I use this code to publish on wall for multiple object properties.
private void publishPhoto(String imageURL) {
Log.d("FACEBOOK", "Post to Facebook!");
try {
JSONObject attachment = new JSONObject();
attachment.put("message",text);
attachment.put("name", "MyGreatAndroidAppTest");
attachment.put("href", "http://stackoverflow.com/users/909317/sunny");
attachment.put("description","Test Test TEst");
JSONObject media = new JSONObject();
media.put("type", "image");
media.put("src", imageURL);
media.put("href",imageURL);
attachment.put("media", new JSONArray().put(media));
JSONObject properties = new JSONObject();
JSONObject prop1 = new JSONObject();
prop1.put("text", "Text or captionText to Post");
prop1.put("href", imageURL);
properties.put(text, prop1);
// u can make any number of prop object and put on "properties" for ex: //prop2,prop3
attachment.put("properties", properties);
Log.d("FACEBOOK", attachment.toString());
Bundle params = new Bundle();
params.putString("attachment", attachment.toString());
facebook.dialog(MyProjectActivity.this, "stream.publish", params, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Log.d("FACEBOOK", "Dialog Success! post_id=" + postId);
Toast.makeText(MyProjectActivity.this, "Successfully shared on Facebook!", Toast.LENGTH_LONG).show();
} else {
Log.d("FACEBOOK", "No wall post made");
}
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
} catch (JSONException e) {
Log.e("FACEBOOK", e.getLocalizedMessage(), e);
}
}
I've solved the second problem about the FacebookException!
There's a wrong line:
setObj.setProperty("score", set.getThisUserScore());
Being "score" a custom property, the line must be replaced by:
setObj.getData().setProperty("score", set.getThisUserScore());
Note that I had to search deeply in the documentation to find this...