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.
Related
I am trying to send app request to my facebook friend after authentication by using the following code snippet.
public void sendApplicationRequest(final List<String> userIdList, final String message, final String title, final int requestCode) {
final Bundle parameters = new Bundle();
parameters.putString("title", title);
parameters.putString("message", message);
parameters.putInt("requestCode", requestCode);
parameters.putString("frictionless", "1");
String to = getListOfUsersAsString(userIdList);
if (to != null) {
parameters.putString("to", to);
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
WebDialog requestDialog = createRequestDialog(parameters);
requestDialog.setOwnerActivity(activity);
requestDialog.show();
}
});
}
private WebDialog createRequestDialog(final Bundle parameters) {
final int requestCode = parameters.getInt("requestCode");
return (
new WebDialog.Builder( activity, "apprequests", parameters))
.setOnCompleteListener(new WebDialog.OnCompleteListener() {
#Override
public void onComplete(Bundle bundle, FacebookException e) {
//...
}
}
).build();
}
The problem is, the dialog shows on top of my app's activity but it requires authentication again. When I enter my credentials and login to facebook on the dialog, everything works well but players have to log in on every app request again and again.
I have also tried the new GameRequestDialog and GameRequestContent API's but the result is the same.
Do you have an idea about what is the problem here which force me to authenticate again on every web dialog?
Correction :
After authenticating on the web dialog for the first time, it never forces you to authenticate again. But still, players need to authenticate two times in total.
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.
I'd like to know the simplest way to update a user's facebook status. I'd like to simply display a 'Share' button. When the user touches 'Share':
If they are already logged in to Facebook, a dialog will appear giving them the option to edit their posting before submitting to Facebook.
If they aren't already logged in to Facebook, the will be prompted to login and then automatically shown the sharing dialog upon successful login.
Is there a simple way to do this, or do I need to implement a separate facebook login flow?
So I think I've got a pretty clean way to do it. I welcome any comments.
I'm posting my entire Facebook Manager class which does the work to login and also to bring up the feed dialog:
public class ManagerFacebook
{
private Activity mActivity;
public void updateStatus(final String name, final String caption, final String description, final String link, final String urlPicture,
final Activity activity, final ListenerShareFacebook listenerShareFacebook)
{
mActivity = activity;
// start Facebook Login
Session.openActiveSession(activity, true, new Session.StatusCallback()
{
// callback when session changes state
public void call(final Session session, SessionState state, Exception exception)
{
if (session.isOpened())
{
publishFeedDialog(name, caption, description, link, urlPicture, listenerShareFacebook);
}
}
});
}
private void publishFeedDialog(String name, String caption, String description, String link, String urlPicture,
final ListenerShareFacebook listenerShareFacebook)
{
Bundle params = new Bundle();
params.putString("name", name);
params.putString("caption", caption);
params.putString("description", description);
params.putString("link", link);
params.putString("picture", urlPicture);
Session session = Session.getActiveSession();
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(mActivity, session, params)).setOnCompleteListener(new OnCompleteListener()
{
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)
{
listenerShareFacebook.onShareFacebookSuccess();
}
else
{
// User clicked the Cancel button
listenerShareFacebook.onShareFacebookFailure("Publish cancelled");
}
}
else if (error instanceof FacebookOperationCanceledException)
{
// User clicked the "x" button
listenerShareFacebook.onShareFacebookFailure("Publish cancelled");
}
else
{
// Generic, ex: network error
listenerShareFacebook.onShareFacebookFailure("Error posting story");
}
}
}).build();
feedDialog.show();
}
}
Also, referenced above is my Listener interface so I can notify my Activity of Facebook related stuff:
public interface ListenerShareFacebook
{
void onShareFacebookSuccess();
void onShareFacebookFailure(String error);
}
I would really recommend this:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "text");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Title");
startActivity(Intent.createChooser(sharingIntent, "Share using"));
This doesn't use facebook sdk but it does use facebook app. In my view most of the people that have smartphones and facebook use this app, and expect to share everything through this app.
Also users might click to share on something else (twitter, sms, g+, email,...)
For me the best supstitute to any facebook sdk.
(you can also attach pictures)
I have tried the tutorial http://developers.facebook.com/docs/mobile/android/build/#sdk and I am able to login successfully. this code provides a dialog to login. But I want to make this as an Activity . Because I have to perform other tasks too from this activity. Like when new activity starts after sucessful login come back to previous (facebook) activity again in previous state of facebook. Please help me.
Thanks
The dialog is only created for the user to log into Facebook. Once they have done that it will return back to the original activity. This is what you are asking for right?
Lets say you want to post a message to facebook.
try {
Log.d(TAG, "postToFaceBook()");
if (facebook == null) {
facebook = new Facebook(API);
String access_token = prefs.getFBAccesTocken();
long expires = prefs.getFBExpiry();
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
}
if (facebook.isSessionValid()) {
Log.d(TAG, "Session is valid");
facebook.extendAccessTokenIfNeeded(this, null);
postToFacebook();
} else {
Log.d(TAG, "not valid");
// Using SSO OAuth
// facebook.authorize(this, new String[] { "publish_stream"
// },new LoginDialogListener());
// Not using SSO
facebook.authorize(this, new String[] { "publish_stream" },
Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
}
} catch (NullPointerException e) {
Log.e(TAG, "An error occurd trying to open facebook app");
If the user has logged onto facebook in the past and has a valid session, it will simply post to Facebook if there is not a valid session it will open up the dialog and try to log in.
The LoginDialogListener() responds to the response of this.
public class LoginDialogListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
Log.d(TAG, "Login response recieved");
prefs.saveToken(facebook.getAccessToken());
prefs.saveExpiry(facebook.getAccessExpires());
facebook.extendAccessTokenIfNeeded(MyActivity.this, null);
Log.d(TAG, "Logged in ");
postToFacebook();
}
}
The other option is to look at using SSO (which I have commented out in the example code).
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;
}
}