Post on Facebook wall without showing dialog on android - android

I am trying to post a feed on Facebook wall without opening a dialogue box using Facebook Android SDK. I tried to find a way but couldn't find. Can anyone tell em how to post to wall in background without opening a dialogue.
I tried using the below code
public static void PublishToFeedInBackground()
{
final Bundle _postParameter = new Bundle();
_postParameter.putString("name", name);
_postParameter.putString("link", link);
_postParameter.putString("picture", link_to_image);
_postParameter.putString("caption", caption);
_postParameter.putString("description", description);
final List<String> PERMISSIONS = Arrays.asList("publish_actions");
if (Session.getActiveSession() != null)
{
// Check for publish permissions
List<String> _permissions = Session.getActiveSession().getPermissions();
if (!isSubsetOf(PERMISSIONS, _permissions))
{
NewPermissionsRequest reauthRequest = new Session.NewPermissionsRequest(this.GetContext(), PERMISSIONS);
Session.getActiveSession().requestNewReadPermissions(reauthRequest);
return;
}
}
this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
Request request = new Request(Session.getActiveSession(), "me/feed", _postParameter, HttpMethod.POST);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
});
}
But it posts my app page details instead of the *_postParameter* i give.
I also tried to use 2 other methods but it didn't post anything
Map<String, Object> params = new HashMap<String, Object>();
params.put("name", name);
params.put("link", link);
params.put("picture", link_to_image);
params.put("caption", caption);
params.put("description", description);
JSONObject jfeed = new JSONObject(params);
final GraphObject _feed = GraphObject.Factory.create(jfeed);
Request.executePostRequestAsync(Session.getActiveSession(), "https://graph.facebook.com/"+userID+"/feed", _feed, new Request.Callback()
{
#Override
public void onCompleted(Response response)
{
Log.i("tag", response.toString());
}
});
Second method is
Request.executeRestRequestAsync(Session.getActiveSession(), "stream.publish", _postParameter, HttpMethod.POST);

I found out what the problem was. I was not asking the right permissions and the graph path was also wrong. The right method is :
public static void PublishToFeedInBackground()
{
final Bundle _postParameter = new Bundle();
_postParameter.putString("name", name);
_postParameter.putString("link", link);
_postParameter.putString("picture", link_to_image);
_postParameter.putString("caption", caption);
_postParameter.putString("description", description);
final List<String> PERMISSIONS = Arrays.asList("publish_stream");
if (Session.getActiveSession() != null)
{
NewPermissionsRequest reauthRequest = new Session.NewPermissionsRequest(this.GetContext(), PERMISSIONS);
Session.getActiveSession().requestNewPublishPermissions(reauthRequest);
}
this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
Request request = new Request(Session.getActiveSession(), "feed", _postParameter, HttpMethod.POST);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
});
}

As far as I know, this was possible with the REST api which is now deprecated... https://developers.facebook.com/docs/reference/rest/
EDIT: here are the functions you can use to post https://developers.facebook.com/docs/reference/rest/#publishing-methods

Related

How to share predefined text on Facebook via ShareDialog Android

i have a big problem for sharing text via ShareDialog. It seems i can only share predefined links,descriptions... but not text. Is there any other way to share text of Facebook from my Android app.
My code is:
FacebookDialog shareDialog = createShareDialogBuilderForLink().build();
private FacebookDialog.ShareDialogBuilder createShareDialogBuilderForLink() {
return new FacebookDialog.ShareDialogBuilder(this)
.setCaption("Here Comes the Boom!!!!")
.setName("Hello Facebook")
.setDescription("Here is my description")
.setLink("http://developers.facebook.com/android");
}
It's impossible, you have to use the Facebook api to do this.
More informations here: https://stackoverflow.com/a/22123047/2065418
Code for Facebook sharing text/link
public void post(String post_text) {
Bundle postParam = new Bundle();
Request.Callback callback = new Request.Callback() {
#Override
public void onCompleted(Response response) {
// shareDialog.dismiss();
// showPublishResult("Photo Post", response.getGraphObject(),
// response.getError());
}
};
Session session = createSession();
postParam.putString("name", post_text);
postParam.putString("link", "https://developers.facebook.com/android");
Request request = new Request(session, "me/feed", postParam,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}

Post message on my friends wall with sdk 3.5 android

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

facebook sharing shows nullpointer exception at jsonobject graphresponse

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..

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

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;
}
}

Share link and text with Android Facebook SDK 3.0

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

Categories

Resources