Facebook Android SDK. Error validating access token - android

I am trying to access user information from facebook sdk.But I keep getting this error.
{"error":{"message":"Error validating access token: The session has been invalidated because the user has changed the password.","type":"OAuthException","code":190,"error_subcode":460}}
Here is the call which returns me the error in the response parameter of the oncomplete function.
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response; //<-- error in response
try {
JSONObject profile = new JSONObject(json);
MainActivity.this.userid = profile.getString("id");
new GetUserProfilePic().execute();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + MainActivity.this.userid, Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
Log.e("jsonexception",e.getMessage());
facebook.extendAccessTokenIfNeeded(MainActivity.this, null);
GetUserInfo();
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
Sometimes I get the correct response also.I think this is due to the access token expiration if I am right.
So can you guys tell me how to extend the access token although I've used this facebook.extendAccessTokenIfNeeded(this, null); in the onResume method of the activity.
How to solve this?

Both the extendAccessTokenIfNeeded and extendAccessTokenIfNeeded methods require the native Facebook app to be installed locally.
(I don't know if you are using v2 or v3b of the SDK, but it's documented here https://developers.facebook.com/docs/reference/android/3.0/Facebook#extendAccessToken(Context,%20ServiceListener) )
The behavior you're seeing... is it in the emulator or a real device? If the former, you can install the native Facebook app as an APK from v3b of the SDK, available here: https://developers.facebook.com/android

Related

Auto post on Facebook from Android game on user behalf

I have developed a physics based (Box2d) game for android using Processing and I want to add score sharing option to it so that the user can share his/her best score on their facebook timeline after the game. I have setup Facebook SDK in eclipse. I have searched over internet and found this solution:
public class FacebookConnector {
private static final String APP_ID = "*************";
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
SharedPreferences mPrefs;
public FacebookConnector() {
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
}
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(LocalPakistaniGames.this,
new String[] { "email",
"publish_stream" }, new DialogListener() {
public void onCancel() {
// Function to handle cancel event
}
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
public void onError(DialogError error) {
// Function to handle error
}
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
public void logoutFromFacebook() {
mAsyncRunner.logout(LocalPakistaniGames.this,
new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
// User successfully Logged out
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Name: " + name + "\nEmail: " + email,
Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onIOException1(IOException e, Object state) {
}
public void onFileNotFoundException1(FileNotFoundException e,
Object state) {
}
public void onMalformedURLException1(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
});
}
public void postToWall(int level, int score) {
// post on user's wall.
String msg = "I just made new best score in Level " + level
+ ". My new Best Score is " + score + ". Beat my score!";
final Bundle parameters = new Bundle();
parameters.putString("description", msg);
parameters.putString("picture", "http://i57.tinypic.com/fui2o.png");
parameters.putString("link",
"https://www.facebook.com/LocalPakistaniGamesAndroid");
parameters.putString("name", "Local Pakistani Games");
parameters.putString("caption",
"Share this. Be a part of preserving Pakistani culture.");
LocalPakistaniGames.this.runOnUiThread(new Runnable() {
public void run() {
facebook.dialog(LocalPakistaniGames.this, "feed",
parameters, new DialogListener() {
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
if (values != null) {
Toast.makeText(LocalPakistaniGames.this,
"Shared successfully on your timeline!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(
LocalPakistaniGames.this,
"Share cancelled!",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(LocalPakistaniGames.this,
"Facebook Error!",
Toast.LENGTH_SHORT)
.show();
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(LocalPakistaniGames.this,
"Error!", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(LocalPakistaniGames.this,
"Share cancelled!",
Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
Its working fine and giving a pre-filled dialog box where user can either share or close the dialog box. I have checked and It's sharing correctly on Facebook timeline. But the problem is that it is not using Facebook app installed on the device. Its using chrome on my device to login to Facebook.
Is there any way to force it to use Facebook app for android instead of going to chrome (or any other browser)??
There are many issues with your use of the Facebook SDK, but I will jump straight to your problem.
You're using the "feed" dialog to share. This is a web dialog, which is why it's popping up a WebView (not the actual browser app). You also do not pass any session or access tokens to the feed dialog, which is why the user needs to login before they can share.
If you want to share using the Facebook app, I would recommend this doc: https://developers.facebook.com/docs/android/share
If you want to properly use the Facebook SDK (rather than the old deprecated one), please start here: https://developers.facebook.com/docs/android/getting-started/
Here is the solution to your problem. If you want to make automatic publications on facebook wall, you have to use graph api.
Also, the first thing that you have to do is login with facebook and after that, you have to do another request for permissions.
If you are using LoginManager:
LoginManager.getInstance().logInWithPublishPermissions(this, Arrays.asList("publish_actions"));
this line of code gives to your app the permissions to make publications in behalf to the user

Facebook sdk not working in tablet (Android) it work fine in phone

In my application i am using Facebook SDK for login in to application. It will work fine without any error in phone but if i am test my in tablet it authorised user and generate the access token also but not fetch the user data. i am follow this link for this code http://sunil-android.blogspot.in/2013/08/facebook-integration-with-android-app.html
i am sharing my imported code part
/**
* Function to login into facebook
* */
#SuppressWarnings("deprecation")
public void loginToFacebook() {
String access_token = obj_pref.get_access_token();
long expires = obj_pref.get_access_expires();
if (access_token != null) {
facebook.setAccessToken(access_token);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "email", "publish_stream",
"user_birthday" }, new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
obj_pref.set_access_token(facebook.getAccessToken());
obj_pref.set_access_expires(facebook.getAccessExpires());
getProfileInformation();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
} else if (facebook.isSessionValid()) {
getProfileInformation();
}
}
/**
* Get Profile information by making request to Facebook Graph API
* */
#SuppressWarnings("deprecation")
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);
obj_pref.set_user_id(profile.getString("email"));
runOnUiThread(new Runnable() {
#Override
public void run() {
new send_fb_data().execute();
// upload user data to my database server
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
can any body help me out for this issue even in tablet it will not give any error ...

How to get facebook user birthday in android?

I use this code to get Facebook user informations. Most of informations are shown but the fact I need is user-birthday. There is no user-birthday in json array. The source code is here. Getting user information code is here
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);
Log.i("profile",profile+"");
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
I need some advices. Please!!!
02-03 21:29:35.700: D/Profile(1350): {"id":"1550015884","name":"Aung Htoon Kyaw","first_name":"Aung","middle_name":"Htoon","last_name":"Kyaw","link":"https:\/\/www.facebook.com\/aung.htoonkyaw","hometown":{"id":"105988982772786","name":"Yangon, Burma"},"location":{"id":"115804185098639","name":"Rangoon, Yangon, Burma"},"work":[{"employer":{"id":"107622942602570","name":"KMMGroup"}}],"favorite_athletes":[{"id":"450149851675417","name":"Gohan Kazuto Uzumaki"},{"id":"339211762793623","name":"Natsu Dragneel"},{"id":"1347550405383513","name":"Instagram Girls"},{"id":"331817313532412","name":"Hinata Hyuga"},{"id":"481643341874600","name":"Erza Scarlet"},{"id":"123163411183595","name":"Sanji"}],"education":[{"school":{"id":"109294362421667","name":"BEST High School"},"year":{"id":"140617569303679","name":"2007"},"type":"High School"},{"school":{"id":"104056766297330","name":"University of Computer Studies, Yangon"},"year":{"id":"141778012509913","name":"2008"},"type":"College","with":[{"id":"1059125424","name":"Nara ChannLynn"}]},{"school":{"id":"106398082730475","name":"UCSY"},"year":{"id":"141778012509913","name":"2008"},"type":"College"}],"gender":"male","email":"waptan22\u0040gmail.com","timezone":6.5,"locale":"en_US","verified":true,"updated_time":"2013-09-12T14:32:54+0000","username":"aung.htoonkyaw"}
This is logcat output.
to get more personal details you need a user permission, so pragmatically you need to add permission to your session and prompt it to the user to accept/deny this permission.
if you are following the Androidhive tutorial, I am afraid it is the old Facebook SKD so you need to read the new version of the SDK, to solve your problem check this page out and specifically Step 2
on snippet of adding permission code:
authButton.setReadPermissions(Arrays.asList("user_location", "user_birthday", "user_likes"));
...

Publishing/Creating a poll from an android app to facebook

There is an application in facebook called poll(opinion poll), where you can give a question and some options. After you create the poll, others can start to vote. Can I create the poll in my android app and publish it in facebook? i.e the user will give his facebook login credentials and teh app will create the poll on his behalf. Are there any such API's?
Yes, it is possible. The relevant documentation is here: https://developers.facebook.com/docs/reference/api/question/
To do this on your android app, you need to add our Facebook SDK for Android to your app. Once you do so, to create a question you just need to do the following
Authenticate the user via Facebook to get a valid access token
Request the publish_stream and user_questions permissions
Then you just need the following code to create a question and publish it to Facebook:
Bundle params = new Bundle();
params.putString("question", "Cats or dogs?");
JSONObject questions = new JSONObject();
questions.put("Cat");
questions.put("Dog");
params.putString("options", questions.toString())
mAsyncRunner.request("me/questions", params, "POST", new RequestListener() {
#Override
public void onComplete(Bundle values) {
// success
Log.d("fb", values.toString());
}
#Override
public void onFacebookError(FacebookError e, final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
#Override
public void onFileNotFoundException(FileNotFoundException e, final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
#Override
public void onIOException(IOException e, final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
#Override
public void onMalformedURLException(MalformedURLException e, final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}

how to change the facebook profile picture using facebook android sdk?

my english is not so perfect but i want to learn, so i hope you can understand me. I wanna know how can i change the facebook profile pic using facebook android sdk. im able to upload pictures from my app to any album, including "Profile Pictures" (i use the next code:)
params=new Bundle();
params.putByteArray("photo", photo);
params.putString("caption", description);
mAsyncRunner.request(idAlbum+"/photos", params,"POST",new RequestListener() {
#Override
public void onMalformedURLException(MalformedURLException e, Object state) {}
#Override
public void onIOException(IOException e,Object state) {}
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state){}
#Override
public void onFacebookError(FacebookError e,Object state) {}
#Override
public void onComplete(String response, Object state) {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Success", Toast.LENGTH_LONG).show();
}
});
}
}, null);
but i dont know how to set the uploaded image as the profile pic. maybe adding some code to this? I know that what i ask is posible using facebook sdk for php. also, i have seen an Apple app that do this too. Then, i think i can do it in android. somebody has information about what im looking for? thanks in advance.
Ok, I found the way to do that. and this is the code:
params=new Bundle();
try {
params.putByteArray("photo", photo);
} catch (IOException e) {
e.printStackTrace();
}
params.putString("caption", description);
mAsyncRunner.request(idAlbum+"/photos", params,"POST",
new RequestListener() {
#Override
public void onMalformedURLException(MalformedURLException
e, Object state) {}
#Override
public void onIOException(IOException e,Object state) {}
#Override
public void onFileNotFoundException(
FileNotFoundException e, Object state){}
#Override
public void onFacebookError(FacebookError e,Object state) {}
#Override
public void onComplete(final String response, Object state) {
mHandler.post(new Runnable() {
#Override
public void run() {
try {
JSONObject json=new JSONObject(response);
JSONObject obj=new JSONObject(
facebook.request("me"));
final String photoId=json.getString("id");
String userId=obj.getString("id");
String url="https://m.facebook.com/photo." +
"php?fbid="+photoId+"&id="+userId+
"&prof&__user="+userId;
Intent mIntent=new Intent(Intent.ACTION_VIEW,
Uri.parse(url));
startActivity(mIntent);
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}, null);
Post the photo on a specific album, get the photoID with a JSONObject, and then redirect to a web page where the user can confirm to set the photo as his/her profile picture.

Categories

Resources