I am using android-facebook-sdk and i am trying to request profile information. But i cant get the response back. I have generated key hash with keytool and pasted it in the facebook app settings. Also i have added app ID in the code. Problem is that i cant get the profile information, or any information at all.
public class StartingPoint extends Activity {
Facebook facebook = new Facebook("actual app id");
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
Button btnt;
/*
* On Create
* */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*
* button Test
* */
btnt = (Button) findViewById(R.id.btntallinn);
btnt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProfileInformation();
}
});
/*
* Get existing access_token if any
*/
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);
}
/*
* Only call authorize if the access_token has expired.
*/
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "email",
"publish_checkins", "rsvp_event", "manage_pages",
"publish_stream", "user_likes", "user_groups" },
new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
facebook.extendAccessTokenIfNeeded(this, null);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
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();
}
}
#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) {
}
});
}
}
Logcat:
03-22 09:38:13.545: D/Profile(23833): {"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}
03-22 09:38:13.545: W/System.err(23833): org.json.JSONException: No value for name
03-22 09:38:13.545: W/System.err(23833): at org.json.JSONObject.get(JSONObject.java:354)
03-22 09:38:13.545: W/System.err(23833): at org.json.JSONObject.getString(JSONObject.java:510)
03-22 09:38:13.545: W/System.err(23833): at com.tana.tallinn.tartu.StartingPoint$3.onComplete(StartingPoint.java:172)
03-22 09:38:13.545: W/System.err(23833): at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:254)
Error says you don't have required access token. try to print facebook.getaccesstoken() and see if you have valid token.with this token you can try in browser to see if you get profile information
Related
I want facebook profile information in my code. This code works Log.e("in try start", "tryyyyyyyyy"); until here but after that not even single log is executed.
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
public void loginToFacebook() {
// mPrefs = getPreferences(SharedPreferences.);
// 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(getActivity(),
new String[] { "email", "publish_actions" },
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
Toast.makeText(getActivity(), "hiiiiii", Toast.LENGTH_SHORT).show();
//mPrefs=getSharedPreferences("data", getActivity().MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
Log.e("getProfileInformation entry", "getProfileInformation");
getProfileInformation();
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
});
}
}
public void getProfileInformation() {
Toast.makeText(getActivity(), "byeeeeeee", Toast.LENGTH_SHORT).show();
Log.e("getProfileInformation start", "getProfileInformation");
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
Log.e("in try start", "tryyyyyyyyy");
JSONObject profile = new JSONObject(json);
// getting name of the user
Log.d("profile", ""+profile);
fb_name = profile.getString("name");
// getting email of the user
fb_email = profile.getString("email");
Log.d("fb_name", "naem"+fb_name+"emial"+fb_email);
//fb_login=true;
// fb_Image = getUserPic(fb_email);
// LoginFuction();
} catch (JSONException e) {
e.printStackTrace();
Log.e("catchhhhhh", ""+e.getMessage());
}
}
public Bitmap getUserPic(String userID) {
String imageURL;
Bitmap bitmap = null;
Log.d("TAG", "Loading Picture");
imageURL = "http://graph.facebook.com/"+userID+"/picture?type=small";
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
} catch (Exception e) {
Log.d("TAG", "Loading Picture FAILED");
e.printStackTrace();
}
return bitmap;
}
#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) {
}
});
}
This code does not give me any name or emailId.
-Hello Abhishek !
- I have tried using Facebook sdk4.+ and i am getting profile info perfectly.
-Firs of all add below code into your oncreate method before setcontentview
FacebookSdk.sdkInitialize(getApplicationContext());
-Then Create you Callbackmanager using below code:-
callbackManager = CallbackManager.Factory.create();
-Add Permissions using below code:-
permission.add("publish_actions");
-Below code is used for Login
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
act,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
if (!TextUtils.isEmpty(object.toString())) {
try {
JSONObject jresJsonObject = new JSONObject(object.toString());
String id = "", name = "", gender = "";
if (!(jresJsonObject.isNull("id"))) {
id = jresJsonObject.getString("id");
}
if (!(jresJsonObject.isNull("gender"))) {
gender = jresJsonObject.getString("gender");
if (gender.equals("male")) {
gender = "0";
} else {
gender = "1";
}
}
if (!(jresJsonObject.isNull("name"))) {
name = jresJsonObject.getString("name");
}
} catch (Exception e) {
}
}
Log.e("graphrequest", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,gender,link");
request.setParameters(parameters);
request.executeAndWait();
}
#Override
public void onCancel() {
Log.i("", "Access Token:: " + "loginResult.getAccessToken()");
}
#Override
public void onError(FacebookException exception) {
Log.i("", "Access Token:: " + "loginResult.getAccessToken()");
}
});
LoginManager.getInstance().logInWithPublishPermissions(this, permission);
-Last but no least add below code in your OnActivitResult
callbackManager.onActivityResult(requestCode, resultCode, data);
NOTE:- This is using latest Facebook sdk
-Please inform me if it is not usefull or you are still getting issue in this.
im my application,i can login to facebook and get the data,but when i click on logout,and then click on login again,it toast the message already login,but i want after logout,on login it again ask the login id and password,as all login requires.in on destroy i tried to clear the session,but it shows an error null exception in onDestroy. please suggest somthing
MainActivity
public class MainActivity extends Activity {
Facebook fb;
Button login,getData,logout;
ImageView ig;
String app_id;
String access_token;
long expires;
private static AsyncFacebookRunner mAsyncRunner;
private SharedPreferences mPrefs;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
app_id= getString(R.string.app_id);
fb= new Facebook(app_id);
login=(Button) findViewById(R.id.login);
logout=(Button) findViewById(R.id.logout);
getData=(Button) findViewById(R.id.getData);
// ig= (ImageView) findViewById(R.id.profile_pic);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
}
});
getData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProfileInformation();
}
});
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(fb.isSessionValid()){
Session.initializeStaticContext(MainActivity.this.getApplicationContext());
logoutFromFacebook();
}
}
});
mAsyncRunner = new AsyncFacebookRunner(fb);
//updateButtonImage();
try {
PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures)
{
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
Log.e("name not found", e.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
}
}
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
access_token = mPrefs.getString("access_token", null);
expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
fb.setAccessToken(access_token);
login.setVisibility(View.VISIBLE);
// Making get profile button visible
getData.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + fb.isSessionValid());
}
if (expires != 0) {
fb.setAccessExpires(expires);
Toast.makeText(MainActivity.this, "already login", Toast.LENGTH_LONG).show();}
if (!fb.isSessionValid()) {
fb.authorize(this,
new String[] { "email", "publish_stream" },
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
editor = mPrefs.edit();
editor.putString("access_token",
fb.getAccessToken());
editor.putLong("access_expires",
fb.getAccessExpires());
editor.commit();
// Making Login button invisible
login.setVisibility(View.VISIBLE);
// Making logout Button visible
getData.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
fb.authorizeCallback(requestCode, resultCode, data);
}
#SuppressWarnings("deprecation")
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
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 onIOException(IOException e, Object state) {
}
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
public void onFacebookError(FacebookError e, Object state) {
}
});
}
#Deprecated
public void logoutFromFacebook() {
mAsyncRunner.logout(MainActivity.this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// make Login button visible
login.setVisibility(View.VISIBLE);
// making all remaining buttons invisible
getData.setVisibility(View.INVISIBLE);
}
});
}
}
#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) {
}
});
}
#Override protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// if(fb.isSessionValid()){
Session.getActiveSession().closeAndClearTokenInformation();
// }
}
}
It is not guaranteed that onDestroy() method will call always called on activity finish.
So better you put that code of session clear in onPause() method.
UPDATE:
Do One more thing
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("access_token", null);
editor.commit();
SharedPreferences.Editor editor2 = getPreferences(MODE_PRIVATE).edit();
editor2.putLong("access_expires", 0);
editor2.commit();
Add this lines in your facebookLogout() method.
Because In your code I found that you are not checking for the session you checking this two variables to identify whether the user is login or not.
You can't rely to onDestroy to be called just after quiting your activity (finish()). it's usually the case but ondestroy can be called after a considerable delay.
you can call your cleaning code in onPause and you can enhance it like following:
#Override protected void onDestroy() {
super.onDestroy();
Session session = Session.getActiveSession();
if (session != null){
session.closeAndClearTokenInformation();
}
}
it is not known when onDestroy is going to call. it only invoke onStop and then move your activity to back. It is happen because if user again start this application , it will not have to load activity in ram again.because it a costly process to load activity in ram. so dont do any saving of data or any other work in onDestroy.move that work in onPause or in onStop.
read more here
I'm implementing Facebook Login in my android app . The problem is When I run the app , it redirects to the facebook login page on the click of a button in my main activity . When I enter the credentials , a white page is displayed and nothing happens . Also , if I run the app a second time , only the blank page shows up . I tried to toggle on/off the single sign on functionality in the developer settings page of facebook , but it didn't help . Here's my code of the Facebook Login activity .
public class FacebookLogin extends Activity {
// Your Facebook APP ID
private static String APP_ID = "xxxxxxx"; // Replace with your App
// ID
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAsyncRunner = new AsyncFacebookRunner(facebook);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// Start AsyncTASK here
loginToFacebook();
} else {
DialogClass
.createDAlertDialog(
FacebookLogin.this,
"Please Check Internet Connection \n Please Turn on Internet",
true);
}
}
/**
* Function to login into facebook
* */
#SuppressWarnings("deprecation")
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);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
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
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
public void onAuthFail(String error) {
Log.e("FB", "AuthFailed: " + error);
Toast.makeText(FacebookLogin.this, "Auth fail",
Toast.LENGTH_LONG).show();
startActivity(new Intent(FacebookLogin.this,
SignIn.class));
}
public void onAuthSucceed() {
Log.e("FB", "AuthSucceed");
Toast.makeText(FacebookLogin.this, "Auth success",
Toast.LENGTH_LONG).show();
startActivity(new Intent(FacebookLogin.this,
Logout.class));
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
/**
* Function to show Access Tokens
* */
public void showAccessTokens() {
String access_token = facebook.getAccessToken();
Toast.makeText(getApplicationContext(),
"Access Token: " + access_token, Toast.LENGTH_LONG).show();
}
/**
* Function to Logout user from Facebook
* */
#SuppressWarnings("deprecation")
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
}
#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 implemented that same for windows phone application. I used to face the same problem. But got it correct.
https://github.com/sravich/MvvmCross-Facebook-Login
You could use this link to check the code and run it in similar fashion for android platform. Logic is the same.
I have same issue mentioned in this stack overflow question. But couldn't find the solution. My problem is when I use facebook login in my android device(which is not installed facebook app), my app works as expected. If I install the facebook application my code doesn't work anymore and It throws the error "Login failed. Please contact the maker of this app and ask them to report issue #1118578 to Facebook". My code is posted below
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAsyncRunner = new AsyncFacebookRunner(facebook);
loginToFacebook();
}
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
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
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
getProfileInformation();
} }); } }
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
/**
* 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);
// 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() {
// getProfileInformation();
String arr[] = name.split(" ", 2);
String name1 = arr[0];
String name2 = arr[1];
Intent intent = new Intent(FacebookLogin.this, UserAccount.class);
/*Sending some arguments*/
Bundle bundle = new Bundle();
bundle.putString("UserName",name1);
bundle.putString("Id", email);
intent.putExtras(bundle);
logoutFromFacebook();
startActivity(intent); }
});
} catch (JSONException e) {
e.printStackTrace();
} } }); }
#SuppressWarnings("deprecation")
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
facebook.setAccessToken(null);
facebook.setAccessExpires(0);
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
// User successfully Logged out
} } }); }
}
Please anyone tell me how can I avoid this error...
I am following this tutorial. I got as far as to the point you retrieve the access token from the savedPreferences and then created a logout button. The problem is, it seems I access_token is always correct, no matter if I logout from my app or even from Facebook app.
This is my code:
public class MainActivity extends Activity {
private String TAG = MainActivity.class.getName();
Facebook mFacebook = new Facebook("whatever");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
private SharedPreferences mPrefs;
//UI elements
private ImageButton fbLoginButton;
private Button getInfoButton;
private Button fbLogoutButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if(access_token != null) {
Log.d(TAG, "Token found. Setting token " + access_token);
mFacebook.setAccessToken(access_token);
}
if(expires != 0) {
Log.d(TAG, "Setting expire " + expires);
mFacebook.setAccessExpires(expires);
}
if(!mFacebook.isSessionValid()) {
mFacebook.authorize(this, new String[] {"email", "read_friendlists" }, new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", mFacebook.getAccessToken());
editor.putLong("access_expires", mFacebook.getAccessExpires());
editor.commit();
Log.d(TAG, "Logging you in");
}
#Override
public void onFacebookError(FacebookError error) {
Log.d(TAG, "Facebook error: " + error.getMessage() );
}
#Override
public void onError(DialogError e) {
Log.d(TAG, "Error: " + e.getMessage());
}
#Override
public void onCancel() {
Log.d(TAG, "User Canceled");
}
});
}
else{
Toast.makeText(this, "Already logged in", Toast.LENGTH_LONG).show();
}
fbLoginButton = (ImageButton) findViewById(R.id.buttonFBLogin);
getInfoButton = (Button) findViewById(R.id.buttonGetInfo);
fbLogoutButton = (Button) findViewById(R.id.buttonLogout);
fbLogoutButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doLogout();
}
});
}
protected void doLogout() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d(TAG, "Logging you 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) {}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
}
I am always getting the Already logged in Toast.Am I doing something wrong?
PS. before retrieving the access_token from sharedpreferences, the app seemed to work fine, so it's not a problem with my API key or my debug key.
Try mFacebook.logout and check reponse value. If logout is successful it will be "true". Works for me.
Don't forget about Single Sign-On feature. If you will be still logged in Facebook app it won't really logout you.