post NOT predifined messages on facebook wall from android application - android

I'm trying to create an android application which would allow the users to post messages on their facebook wall and also on their friends wall.
I've been through a few tutorials but in each of them is done barely the same thing:integrate facebook in application, the login authorization and posting a predifined message on the walll.
I'm using facebook sdk and I wonder is possible for the user to write directly to his wall in a dialog window???
What kind of authorization I need and if u could give me an example would be great.Thank u!

Take a look at this tutorial here and there is part 2 here. It will guide you though setting up the application to use facebook. Once you have all that setup you can use a function like this to post a msg to someones wall:
/**
* Post to a friends wall
* #param msg Message to post
* #param userId Id for friend to post to or null to post to users wall
*/
public void postToWall(String msg, String userID) {
try {
if (isSession()) {
String response = mFacebook.request((userID == null) ? "me" : userID);
Bundle parameters = new Bundle();
parameters.putString("message", msg);
response = mFacebook.request(((userID == null) ? "me" : userID) + "/feed", parameters, "POST");
Log.d(TAG,response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
} catch(Exception e) {
e.printStackTrace();
}
}

Related

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.

Not able to post on facebook wall in every one minute

I am developing one android application , in that application i want to post message on facebook in every 1 minute.
There is no problem in my code . In Every one minute i call the following method and it call successfully everytime , but in facebook i am not able to see all the post, facebook can only show the post after every ten minutes.
Code .
public void postOnWall(String msg)
{
try
{
if(mFacebook != null)
{
String response = mFacebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putString("description", "");
response = Profile.mFacebook.request("me/feed", parameters,"POST");
if (response == null || response.equals("") || response.equals("false"))
{
Log.v("Error", "Blank response");
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Can you tell me what is the exact problem , why i can't see all the post on wall ? I can only see the post of every 10 Min.

OAuthException when trying to Post to Friends Wall

Im having alot of trouble trying to post to a friends wall using the Facebook api in Android. This is what I have at the moment:
if (facebook.isSessionValid()) {
String response = facebook.request((userID == null) ? "me" : userID);
Bundle params = new Bundle();
params.putString("message", "put message here");
params.putString("link", "http://mylink.com");
params.putString("caption", "{*actor*} just posted this!");
params.putString("description", "description of my link. Click the link to find out more.");
params.putString("name", "Name of this link!");
params.putString("picture", "http://mysite.com/picture.jpg");
response = facebook.request(((userID == null) ? "me" : userID) + "/feed", params, "POST");
Log.d("Tests",response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} else {
// no logged in, so relogin
Log.d("1234567890", "sessionNOTValid, relogin");
}
}catch(Exception e){
e.printStackTrace();
}
But this returns with this error:
12-11 21:34:06.604: D/FACEBOOK RESPONSE(14954): {"error":{"message":"(#200) Feed story publishing to other users is disabled for this application","type":"OAuthException","code":200}}
You probably created this Facebook application recently, which means the February 2013 breaking changes are enabled.
February's Breaking Changes include:
Removing ability to post to friends walls via Graph API
We will remove the ability to post to a user's friends' walls via the Graph API. Specifically, posts against [user_id]/feed where [user_id] is different from the session user, or stream.publish calls where the target_id user is different from the session user, will fail. If you want to allow people to post to their friends' timelines, invoke the feed dialog. Stories that include friends via user mentions tagging or action tagging will show up on the friend’s timeline (assuming the friend approves the tag). For more info, see this blog post.
We are disabling this feature starting in February, if you wish to enable it (only temporarily until February), go to your app dashboard > Settings > Advanced > Disable "February 2013 Breaking Changes"
I highly recommend against doing so, however, since starting February this functionality will cause your app to throw the same error again.
I have the solution that might help you, I am using this for my code and its working fine..
private void publishFeedDialog(String friend_uid) {
try{
Session mCurrentSession = Session.getActiveSession();
SessionTracker mSessionTracker = new SessionTracker(
getBaseContext(), new StatusCallback() {
public void call(Session session, SessionState state,
Exception exception) {
}
}, null, false);
String applicationId = Utility
.getMetadataApplicationId(getBaseContext());
mCurrentSession = mSessionTracker.getSession();
if (mCurrentSession == null
|| mCurrentSession.getState().isClosed()) {
mSessionTracker.setSession(null);
Session session = new Session.Builder(getBaseContext())
.setApplicationId(applicationId).build();
Session.setActiveSession(session);
mCurrentSession = session;
}
if (!mCurrentSession.isOpened()) {
Session.OpenRequest openRequest = null;
openRequest = new Session.OpenRequest(
NewFriendList.this);
if (openRequest != null) {
openRequest
.setDefaultAudience(SessionDefaultAudience.FRIENDS);
openRequest.setPermissions(Arrays.asList("email", "publish_actions"));
openRequest
.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
mCurrentSession.openForPublish(openRequest);
}
}
if (regobj != null && friend_uid != null ) {
final Activity activity = this;
Bundle params = new Bundle();
//This is what you need to post to a friend's wall
params.putString("from", "" + regobj.MyFBID);
params.putString("to", friend_uid);
//up to this
params.putString("name", "Facebook SDK for Android");
params.putString("caption", "Build great social apps and get more installs.");
params.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
params.putString("link", "https://developers.facebook.com/android");
params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(this, mCurrentSession, 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) {
Toast.makeText(activity,
"Posted story, id: "+postId,
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(activity,
"Publish cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(activity,
"Publish cancelled",
Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(activity,
"Error posting story",
Toast.LENGTH_SHORT).show();
}
}
}).build();
feedDialog.show();
}
}catch(Exception e)
{
Log.d("Error", ""+e.toString());
}
}
This code will work for only one user, if you want to send it to multiple user then you can use RequestsDialogBuilder instead of WebDialog.

how to to disable facebook feed dialog

I had used a facebook app to post message on wall from https://github.com/facebook/facebook-android-sdk.
Here after user allows the app to use his/her profile, dialog feed comes with an editable area to publish or skip. I want a predefined message there but user will not be able to modify it. I am able to send the predifined message but its editable. How to make it uneditable.
Does any one knows how to do it??
You can just use a function to post directly to the users wall. Just make sure that it is clear to the user that the button posts directly, perhaps use a dialog to get them to confirm they want to post. Here is the code I use:
/**
* Post to a friends wall
* #param msg Message to post
* #param userId Id for friend to post to or null to post to users wall
*/
public void postToWall(String msg, String userID) {
Log.d("Tests", "Testing graph API wall post");
try {
if (isSession()) {
String response = mFacebook.request((userID == null) ? "me" : userID);
Bundle parameters = new Bundle();
parameters.putString("message", msg);
response = mFacebook.request(((userID == null) ? "me" : userID) + "/feed", parameters, "POST");
Log.d(TAG,response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
} catch(Exception e) {
e.printStackTrace();
}
}
The dialog contains a WebView that loads the actual content from a Facebook URL. So to modify the editable area, you would need to modify the DOM of this webpage. See this question for more information about doing that. It is unclear to me from the answers in that question if this is possible. If it is, you'll need to add the code to the FbDialog class in the Facebook Android SDK.

send an invitation to facebook friends to join my website

I have build an android application in which I've integrated faceboook using the facebook-sdk package.I've also succeded to retrieve in my application the name of all my facebook friends, their names and their id's.Further I want to send from my application an invitation to all facebook friends to join a website.Can u point me in the right direction cause I haven't found anything on the internet.Thank you
Try using the code below, if you follow the tutorials i gave you in your other question it will work no probs!
protected void postOfferToWall(String userID){
try {
if (isSession()) {
String response = mFacebook.request((userID == null) ? "me" : userID);
Bundle params = new Bundle();
params.putString("message", "message goes here");
params.putString("link", "http://mysite.com");
params.putString("caption", "Click the link");
params.putString("description", "description of link");
params.putString("name", "name of link");
params.putString("picture", "http://url.to.my.picture/pic.jpg");
response = mFacebook.request(((userID == null) ? "me" : userID) + "/feed", params, "POST");
Log.d("Tests",response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
}catch(Exception e){
e.printStackTrace();
}
}
For a quick reference using the Graph API to post to your friends wall, see Graph API - Facebook Developers. There is a subsection called Publishing, where they use curl to post to a friends wall. Of course you need to get the access tokens and permissions to do such activities but it is all explained here.

Categories

Resources