Sharing a wall post by facebook android sdk - android

Hi I am new to android programming. I want to share a image with some description on facebook.
I have tried every method explain in answers on stackoverflow. My problem is facebook dialog opens but it doesn't have specified bundle parameters.
Please help me with this. I have already tried almost 20 different code snippets. Please give me fully functional code.
#Override
public void onClick(View v) {
fb = new Facebook(app_id);
Bundle par = new Bundle();
par.putString("name", "Ass");
fb.dialog(con,"feed",par, new DialogListener(){
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle arg0) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError arg0) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError arg0) {
// TODO Auto-generated method stub
}});
}
});
}

Have you already set up the facebook side of the application on the development page?
You need to have your app registered on facebook if you are intending to use their api and/or do graph requests or wall posts on behalf of a user authtoken.
You should read this tutorial (check part 5 for fb app registering) and all of the related info around it to really get going with facebook interaction within your app.
I know I did and end up creating my own library for log-in short-cuts or graph requests etc... it's not that simple, it will take you some time aswell.
Also;
Are you using the loginButton from the sdk? Like this:
<com.facebook.widget.LoginButton
android:id="#+id/authButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
/>
It automatically handles user login to facebook whether he has the facebook app installed or not and retrieves a session status result (onStatusChange callback).
Make sure you handle that right first and that the session is correctly initiated.
Still, posting your log will give us a better idea of what you encountering with.
I have to say, tho, that the facebook api for android is pretty solid so far so you must be doing something wrong for sure.
<<<<<< EDIT: >>>>>>
Ok then, assuming you have the user correctly logged-in (session.getActiveSession() == Session.OPENED I believe), the next step is to make sure you enabled necessary permissions.
This example is from the official facebook documentation, try it (execute publishStory() in your app):
private void publishStory() {
Session session = Session.getActiveSession();
if (session != null){
// 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);
return;
}
Bundle postParams = new Bundle();
postParams.putString("name", "Facebook SDK for Android");
postParams.putString("caption", "Build great social apps and get more installs.");
postParams.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
postParams.putString("link", "https://developers.facebook.com/android");
postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i(TAG,
"JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getActivity()
.getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity()
.getApplicationContext(),
postId,
Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
The code issues a POST to the users feed wall with the graph params specified at the bundle.
If session does not have the needed publish permissions, then a permission request will be issued instead. If user granted those permissions, then the RequestAsyncTask should be executed next time you call the method.
As you can see the basic idea is to get the user to log-in with his facebook account (first step), then request necessary permissions for the action, in this case, publish permissions for a wall post (second step), and lastly issue a graph request into "me/feed" with the params needed for the wall post.
In any case, if you still encountering problems please try to debug from your log as it indicates wether the request failed because of invalid session or no permissions etc...
Post your log here in that case , but this should work.

Related

How to share posts and deep link to my android app

I'm trying to implement deep linking in my Android app, so far I can post to my wall but only posts that are really links that goes to google.com (obviously this is a test link). I want the user to be navigated to my app when clicking on the post through the Facebook app, please I need a step by step guide as am not that old in android programming. Here's my code:
private void sharePost() {
// code for sharing the post on facebook
Session session = Session.getActiveSession();
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSIONS));
Bundle postParams = new Bundle();
postParams.putString("name", "JSON Twitter");
postParams.putString("app_name", "JSON Twitter");
postParams.putString("package", "com.example.jsontwitter");
postParams.putString("url", "com.example.jsontwitter");
postParams.putString("caption", "Hello, anyone there ?!");
postParams.putString("description", "This is a description");
postParams.putString("link", "https://google.com");
postParams.putString("class", "com.example.jsontwitter.MainActivity");
new Request(session, "me/feed", postParams,
HttpMethod.POST, new Request.Callback() {
public void onCompleted(Response response) {
/* handle the result */
}
}).executeAsync();
}
One facebook status callback implemetation needed
private Session.StatusCallback mFBStatuscallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
Then i dont know what permission you have give.
But the permission i gave was
private static final List<String> PERMISSION = Arrays
.asList("publish_actions","publish_stream");
new permission request
set the default audience and the send the callback object(mFBStatuscallback)
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
(Activity) mCtx, PERMISSION).setDefaultAudience(SessionDefaultAudience.FRIENDS)
.setRequestCode(100).setCallback(mFBStatuscallback);
session.requestNewPublishPermissions(newPermissionsRequest);
And rest all same as your's. I hope it will work.
Note If you keep pressing on post button for many time only one time the message gets posted. After that it takes some interval to post another message. Its a default behavior of facebook

Android Facebook FeedDialogBuilder post privacy/audience

I'm trying to allow a user to post there status to their FB wall from with in my Android app. I'm having a problem with the Privacy/Audience for the post is always set to "Only Me" I want to set this to "Friends", but I can't find a way to do this. Below is my code snippet of how i'm accomplishing this:
Bundle params = new Bundle();
params.putString("description", " ");
params.putString("name", "testtest app");
params.putString("link", "http://www.testtestapp.com/");
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(QuickCalc.this, 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) {
} else {
// User clicked the Cancel button
}
} else {
// Generic, ex: network error
}
}
})
.build();
feedDialog.show();
The audience level is set when the user first authorizes your app with write permissions, and cannot be changed by the app (for pretty obvious reasons).
When you ask for write permissions, you can request a certain default audience level by calling the setDefaultAudience method, but the user can edit the app settings from the Facebook website, and change the audience setting at any time.

Can't read pages liked by the user using Facebook Graph API

i am new to facebook development on android. My target is to get the list of page names liked by a user. I am using the fallowing code for that.
I want to make sure that i am using the latest facebook sdk and none of the classes or methods i am using are deprecated
ArrayList<String> permissions = new ArrayList<String>();
permissions.add("user_likes");
loginButton.clearPermissions();
loginButton.setReadPermissions(permissions);
loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
if(user != null)
{
Log.d(TAG,"User login successful:"+user.getProperty("favorite_teams"));
Session session = Session.getActiveSession();
if(session !=null && session.isOpened())
{
if(session.getPermissions().contains("user_likes"))
{
requestForPageLikes = new Request(session, "https://graph.facebook.com/me/likes");
requestForPageLikes.setCallback(new Request.Callback() {
#Override
public void onCompleted(Response response) {
GraphObject go = response.getGraphObject();
JSONObject jso = go.getInnerJSONObject();
Log.d(TAG,"Facebook response:"+jso.toString());
}
});
Request.executeAndWait(requestForPageLikes);
}
}
}
}
}
The above request is working fine and i am getting the response code as 200, which is OK.
but the log message is printing as
Facebook response:{"id":"https://graph.facebook.com/me/likes"}
I am sure that there are pages which the user has liked, and my app is configured well in developers.facebook.com and as we see in the above code i have the permission user_likes which is required to read the like pages.
I am heavily stuck with this issue. Any help would be really appreciated.

android facebook: Not showing my Message in dialog

I am working on facebook android application but there is one problem i am facing
i am using the following example
Android/Java -- Post simple text to Facebook wall?
so the problem is that everything works here fine, the dialogs etc etc but When it open the screen to upload Walla Message that i have setted up here
try
{
System.out.println("*** IN TRY ** ");
Bundle parameters = new Bundle();
parameters.putString("message", "this is a test");// the message to post to the wall
facebookClient.dialog(this, "stream.publish", parameters, this);// "stream.publish" is an API call
}
catch (Exception e)
{
// TODO: handle exception
System.out.println(e.getMessage());
}
It does not show me my Message written in the dialog. Whats the problem with that
can anybody Guide me please..
Thanks alot.
Message has been ignored. You can read about it here: https://developers.facebook.com/docs/reference/dialogs/feed/
This field will be ignored on July 12, 2011 The message to prefill the text field that the user will type in. To be compliant with Facebook Platform Policies, your application may only set this field if the user manually generated the content earlier in the workflow. Most applications should not set this.
Use this code , it working for me :
Bundle parameters = new Bundle();
parameters.putString("message",sharetext.getText().toString());// the message to post to the wall
//facebookClient.dialog(Jams.this, "stream.publish", parameters, this);// "stream.publish" is an API call
facebookClient.request("me/feed", parameters, "POST");
Hope it helps..
Edited:
public class FacebookActivity implements DialogListener
{
private Facebook facebookClient;
private LinearLayout facebookButton;
public FacebookActivity(Context context) {
facebookClient = new Facebook();
// replace APP_API_ID with your own
facebookClient.authorize(Jams.this, APP_API_ID,
new String[] {"publish_stream", "read_stream", "offline_access"}, this);
}
#Override
public void onComplete(Bundle values)
{
if (values.isEmpty())
{
//"skip" clicked ?
}
// if facebookClient.authorize(...) was successful, this runs
// this also runs after successful post
// after posting, "post_id" is added to the values bundle
// I use that to differentiate between a call from
// faceBook.authorize(...) and a call from a successful post
// is there a better way of doing this?
if (!values.containsKey("post_id"))
{
try
{
Bundle parameters = new Bundle();
parameters.putString("message",sharetext.getText().toString());// the
message to post to the wall
//facebookClient.dialog(Jams.this, "stream.publish", parameters,
this);// "stream.publish" is an API call
facebookClient.request("me/feed", parameters, "POST");
sharetext.setText("");
Toast.makeText(Jams.this,"Message posted
successfully.",Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
// TODO: handle exception
// System.out.println(e.getMessage());
}
}
}
#Override
public void onError(DialogError e)
{
return;
}
#Override
public void onFacebookError(FacebookError e)
{
return;
}
#Override
public void onCancel()
{
return;
}
}

Android Facebook .. how to get AccessToken

Hi I am trying to add facebook connect to my Android app , I did managed to post on my wall with app but when I downloaded android facebook app and logged in on it but now I cant post on my wall. I am getting this error:
{"error":{"type":"OAuthException","message":"An active access token
must be used to query information about the current user."}}
CODE:
public class FacebookLogin extends Activity {
private static final String APP_API_ID = "080808998-myappId";
Facebook facebook = new Facebook(APP_API_ID);
private AsyncFacebookRunner mAsyncRunner;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAsyncRunner = new AsyncFacebookRunner(facebook);
SessionStore.restore(facebook, this);
SessionEvents.addAuthListener(new SampleAuthListener());
Log.i("Error", facebook.getAccessToken()+"tokenId");
facebook.dialog(FacebookLogin.this, "feed", new SampleDialogListener());
}
public void postOnWall(String msg) {
try {
Bundle bundle = new Bundle();
bundle.putString("message", msg);
bundle.putString("from", "fromMe");
bundle.putString("link","facebook.com");
bundle.putString("name","name of the link facebook");
bundle.putString("description","some description here");
//bundle.putString(Facebook.TOKEN, accessToken);
bundle.putString("picture", "http://url to image");
String response = facebook.request("me/feed",bundle,"POST");
Log.d("Error", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
THe token I am getting is null.
You didn't check if the session is valid or not.
If not, then you have to authorize.
You also have to sign in to Facebook the first time to use your app and give the permissions to the app.
Then you will get the access token for the first time.
Then you should store your session and when using the app again you will not get this error.
To do so, please review the Example application LoginButton.java init() method from Facebook_Android_SDK
Note: make a boolean flag stored in your sharedPreferences to indicate if this is the first time or not,
so the login dialog doesn't pop up every time you use the application.

Categories

Resources