I am attempting to publish to facebook with custom opengraph objects. I am not getting any error on running the code, but no posts are published either.
I refered to the following tutorial for the code.
https://developers.facebook.com/docs/android/share-using-the-object-api/
This is my code.
// Check for publish permissions
Log.w("FBShare", "Publish Story not null");
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
Log.w("FBShare", "has permission");
return;
}
progressDialog = ProgressDialog.show(this, "", "LOADING..", true);
RequestBatch requestBatch = new RequestBatch();
OpenGraphObject match = OpenGraphObject.Factory
.createForPost("cricdecode:match");
match.setTitle("My match");
match.getData().setProperty("my_team", "Team A");
match.getData().setProperty("opponent", "Team B");
match.getData().setProperty("venue", "some plc");
// Set up the object request callback
Request.Callback objectCallback = new Request.Callback() {
#Override
public void onCompleted(Response response) {
// Log any response error
FacebookRequestError error = response.getError();
if (error != null) {
dismissProgressDialog();
Log.w("FBShare", "error");
}
}
};
Request objectRequest = Request.newPostOpenGraphObjectRequest(
Session.getActiveSession(), match, objectCallback);
objectRequest.setBatchEntryName("objectCreate");
requestBatch.add(objectRequest);
requestBatch.executeAsync();
OpenGraphAction playAction = OpenGraphAction.Factory
.createForPost();
playAction.setProperty("match", "{result=objectCreate:$.id}");
// Set up the action request callback
Request.Callback actionCallback = new Request.Callback() {
#Override
public void onCompleted(Response response) {
dismissProgressDialog();
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(
MainActivity.main_context
.getApplicationContext(),
"Error 1: "+error.getErrorMessage(), Toast.LENGTH_LONG)
.show();
} else {
String actionId = null;
try {
JSONObject graphResponse = response
.getGraphObject().getInnerJSONObject();
actionId = graphResponse.getString("id");
} catch (JSONException e) {
}
Toast.makeText(
MainActivity.main_context
.getApplicationContext(),
actionId, Toast.LENGTH_LONG).show();
}
}
};
// Create the publish action request
Request actionRequest = Request.newPostOpenGraphObjectRequest(
Session.getActiveSession(), match, actionCallback);
// Add the request to the batch
requestBatch.add(actionRequest);
I guess FingerPrint and Hash code what you generated might me different. If you still facing the same problem follow the below link to generate a new Hash key from your machine,
Key hash for Android-Facebook app
Place the generated Hash key in your Face book developer account and try again.
I guess the problem is here:
// Create the publish action request
Request actionRequest = Request.newPostOpenGraphObjectRequest(
Session.getActiveSession(), match, actionCallback);
Change it to :
// Create the publish action request
Request actionRequest = Request.newPostOpenGraphActionRequest(
Session.getActiveSession(), playAction, actionCallback);
The problem is that you are calling executeAsync() before adding the actionRequest to the batch. Thus, you just create the object but no action is performed.
Change your code to:
// Add the request to the batch
requestBatch.add(actionRequest);
requestBatch.executeAsync();
Related
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
Working on Facebook. Unable to get publish_actions permission. Using this code:
session.requestNewPublishPermissions(new
Session.NewPermissionsRequest(this, PERMISSION));
any solution...
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private boolean pendingPublishReauthorization = false;
in onActivityResult do this
Session session = Session.getActiveSession();
if (session != null) {
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermsnRequest = new Session.NewPermissionsRequest(
this, PERMISSIONS);
session.requestNewPublishPermissions(newPermsnRequest );
return;
}
}
Also implement this in your class.
private boolean isSubsetOf(Collection<String> a,
Collection<String> b) {
for (String string : a) {
if (!b.contains(string)) {
return false;
}
}
return true;
}
By doing this you will be able to get all the public permissions. you have to open the session after getting read permissions and then only request for publish permissions.
Facebook sdk only returns read-permission, but not the write permissions. You can user the "/me" endpoint to get all the permissions.
final Bundle permBundle = new Bundle();
permBundle.putCharSequence("permission", "publish_actions");
GraphRequest request = new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/me/permissions", permBundle, HttpMethod.GET,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse graphResponse) {
Log.d(TAG, "response2: " + graphResponse.getJSONObject());
try {
JSONArray permList = (JSONArray) graphResponse.getJSONObject().get("data");
if(permList.length() == 0){
// no data for perms, hence asking permission
askForFBPublishPerm();
}else{
JSONObject permData = (JSONObject) permList.get(0);
String permVal = (String) permData.get("status");
if(permVal.equals("granted")){
postToFB();
}else{
askForFBPublishPerm();
}
}
} catch (JSONException e) {
Log.d(TAG, "exception while parsing fb check perm data" + e.toString());
}
}
}
);
request.executeAsync();
i want to post message on my friends wall , I got my friend list and their Id now i am using the below code but it not posting any message to my any of friend wall, i'll post my code, in my above code i am using a static id of my friends but it is not posting any message on my friends wall , if i replace the id with my fb id then it is posting on my wall?
private void getfriendlist()
{
Session.openActiveSession(this, true, new Session.StatusCallback()
{ // callback when session changes state #SuppressWarnings("deprecation")
#Override
public void call(final Session session, SessionState state, Exception exception) { if(session.isClosed())
{
Log.i("postStatusUpdate session.isClosed", "message not posted session is closed");
} if (session.isOpened())
{ // Log.i("session.isOpened", "session.isOpened"); //session.requestNewReadPermissions(newPermissionsRequest);
if (!session.isOpened())
{ Session.OpenRequest openRequest = null;
openRequest = new Session.OpenRequest(InvitefriendsActivity.this);
if (openRequest != null) { //openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS); openRequest.setPermissions(Arrays.asList("email,user_birthday,user_location,user_hometown,user_about_me,user_relationships,publish_stream,publish_actions,basic_info,status_update","friends_birthday","read_friendlists")); //openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK); session.openForRead(openRequest);
} }
Request.executeMyFriendsRequestAsync(session, new Request.GraphUserListCallback()
{
#Override public void onCompleted(List<GraphUser> users, Response response) { Log.d("AL",""+response.toString());
for (int i=0;i<users.size();i++)
{ //Log.d("AL",""+users.get(i).toString());
Log.d("AL",""+users.get(i).getId());
Log.d("AL",""+users.get(i).asMap().get("name"));
Bundle params = new Bundle();
params.putString("message", "Hi ");
params.putString("caption", "Hello");
Request request = new Request(session, "100005147887121/feed", params, HttpMethod.POST); RequestAsyncTask task = new RequestAsyncTask(request); task.execute(); } } }); } } }); }
I think this is related to requested Permissions. Are you (you Session) allowed to post to someone else Wall? You will find here a list of available permissions
https://developers.facebook.com/docs/reference/login/extended-permissions/
I think you need to request for 'publish_actions'
Regards
Michael
I want to publish link if the user is logged in facebook and if not make user logged in and then publish link but it shows NullPointerException at jsonobject graphresponse in the publishlink() method.
Following is my code..
public static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
public static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
public boolean pendingPublishReauthorization = false;
private Session.StatusCallback statusCallback = new SessionStatusCallback();
public void ShareOnFacebook(String sharingpath)
{
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
Session session = new Session.Builder(getBaseContext()).build();
Session.setActiveSession(session);
currentSession = session;
}
else if (!currentSession.isOpened()) {
// Ask for username and password
OpenRequest op = new Session.OpenRequest(this);
op.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
op.setCallback(statusCallback);
List<String> permissions = new ArrayList<String>();
permissions.add("publish_stream");
op.setPermissions(permissions);
Session session = new Session(this);
Session.setActiveSession(session);
Log.d("session", "opening sesion for publish action!!");
session.openForPublish(op);
}
}
private class SessionStatusCallback implements Session.StatusCallback
{
#Override
public void call(final Session session, SessionState state, Exception exception)
{
//we have callback here
if (session.isOpened())
{
Log.d("session", "session is already opened ,we are in the callback section...going to publish link!!");
PublishLink();
}
}
}
public void PublishLink()
{
SharedPreferences prefs = getSharedPreferences("shared",MODE_PRIVATE);
String path = prefs.getString("path", "");
Session session = Session.getActiveSession();
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this,PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
}
Bundle postParams = new Bundle();
postParams.putString("link", path);
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
Log.d("graphresponse", response.toString());
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.d(
"JSON error "+ e.getMessage(), postId);
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(
getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(
getApplicationContext(),
postId,
Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
public boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
Log.d("data", "data coming to onactivityresult: "+data);
}
The problem here is that the requestNewPublishPermissions() method is an asynchronous request, and when you call it, it returns immediately, but at that point, you don't have the publish permissions yet.
What you're doing is making a "publish" request, regardless of whether you have the publish permissions yet, and so the response is going to have an error rather than a GraphObject result.
If you check the response.getError(), you'll likely see a permission error (you should always check that first, before accessing anything else in the Response).
Have a look at the HelloFacebook sample on how to temporarily cache the information you want to post (while you wait for the requestNewPublishPermissions to finish), and only post when you have all the permissions necessary.
finally figured out there was error in
Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);
so change it to
Request request = Request.newStatusUpdateRequest(session, path, callback);
hope this helps someone who have this problem.
so we donot need to create new Bundle anymore ....
we can remove create Bundle and postparams.putString lines in above code..
Im trying to upgrade to the Facebook SDK 3.0 and have finally gotten everything to work with Request.newStatusUpdateRequest(). However my app shares/posts text along with a link. I have tried/looked into the following:
Request.newStatusUpdateRequest()
This does not seem to have any options for a Bundle or any other way to include a link and icon.
Request.newRestRequest()
Skipped this because I saw REST was being depreciated.
new WebDialog.FeedDialogBuilder(_activity, session, params).build().show();
This actually works pretty well but the resulting post does not seem to be linked to my Facebook App and I am not sure how this will effect my Facebook insights.
Request.newPostRequest()
From what I have read, this method seems to be the proper way. However, i cannot figure out where to get the GraphObject to pass in as one of the parameters.
What is the PROPPER way to post/share text, link and image to the user's wall? It seems to be Request.newPostRequest() so I will include the code I have for that.
Request request = Request.newPostRequest(session, "me/feed", ??graph_object??, new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult("message", response.getGraphObject(), response.getError());
}
});
request.setParameters(params);
Request.executeBatchAsync(request);
But what really is a GraphObject? Where do i get the graph_object? The more I read from FB on GraphObject/OpenGraph/Graph API the more I get confused.
If I am heading down the wrong direction entirely, please tell me. If Request.newPostRequest is the propper way of doing this, please give me more information on the GraphObject param.
Finally managed to get everything I needed with the Facebook SDK 3.0 using the following:
Bundle params = new Bundle();
params.putString("caption", "caption");
params.putString("message", "message");
params.putString("link", "link_url");
params.putString("picture", "picture_url");
Request request = new Request(Session.getActiveSession(), "me/feed", params, HttpMethod.POST);
request.setCallback(new Request.Callback() {
#Override
public void onCompleted(Response response) {
if (response.getError() == null) {
// Tell the user success!
}
}
});
request.executeAsync();
I did by using this method.
See if this can help or not.
public static void publishFeedDialog(final Activity current, final String title,
final String caption, final String description, final String link,
final String pictureUrl) {
// start Facebook Login
Session.openActiveSession(current, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
Bundle params = new Bundle();
params.putString("name", title);
params.putString("caption", caption);
params.putString("description", description);
params.putString("link", link);
params.putString("picture", pictureUrl);
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(
current, Session.getActiveSession(), params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
// When the story is posted, echo the
// success
// and the post Id.
final String postId = values
.getString("post_id");
if (postId != null) {
ToastHelper.MakeShortText("Posted");
} else {
// User clicked the Cancel button
ToastHelper
.MakeShortText("Publish cancelled");
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
ToastHelper
.MakeShortText("Publish cancelled");
} else {
// Generic, ex: network error
ToastHelper
.MakeShortText("Error posting story");
}
}
}).build();
feedDialog.show();
}
}
});
To share page or link
Bundle params = new Bundle();
params.putString("link", "link_url");
Request request = new Request(Session.getActiveSession(), "me/feed", params, HttpMethod.POST);
request.setCallback(new Request.Callback() {
#Override
public void onCompleted(Response response) {
if (response.getError() == null) {
// Tell the user success!
}
}
});
request.executeAsync();
For more post parameters see me/feed on developer.facebook.com