Facebook Android Tutorial logout - android

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.

Related

Facebook SDK 3.0 Logout Not Working in android Application from any other Intent

I am using Facebook login in android app,Its Login Successfully .
after Successful login intent goes to next page.
from Second page i am trying to logout the Facebook ,its not Working
Help me to resolve it.
else suggest me Working example for Facebook Login,logout,Getting profile information Latest SDK4.2.
Link I have used
My Logout method
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)
{
//Logout Successss
}
}
});
}
This My Facebook Login Code
AndroidFacebookConnectActivity.java
public class AndroidFacebookConnectActivity extends Activity {
// Your Facebook APP ID
private static String APP_ID = "*************" ; // 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;
// Buttons
Button btnFbLogin;
Button btnFbGetProfile;
Button btnPostToWall;
Button btnShowAccessTokens;
Button Logout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
btnFbGetProfile = (Button) findViewById(R.id.btn_get_profile);
btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
btnShowAccessTokens = (Button) findViewById(R.id.btn_show_access_tokens);
Logout=(Button)findViewById(R.id.btn_show_Logout);
mAsyncRunner = new AsyncFacebookRunner(facebook);
/**
* Login button Click event
* */
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
}
});
/**
* Getting facebook Profile info
* */
btnFbGetProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProfileInformation();
}
});
/**
* Posting to Facebook Wall
* */
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
/**
* Showing Access Tokens
* */
btnShowAccessTokens.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showAccessTokens();
}
});
Logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Logout Button CLicked", "button Clicked");
logoutFromFacebook();
}
});
}
/**
* Function to login into 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);
btnFbLogin.setVisibility(View.INVISIBLE);
// Making get profile button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
Logout.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
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
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
// Making Login button invisible
btnFbLogin.setVisibility(View.INVISIBLE);
// Making logout Button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
Logout.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);
facebook.authorizeCallback(requestCode, resultCode, data);
}
/**
* Get Profile information by making request to Facebook Graph API
* */
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() {
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) {
}
});
}
/**
* Function to post to facebook wall
* */
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
/**
* 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
* */
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() {
// make Login button visible
btnFbLogin.setVisibility(View.VISIBLE);
// making all remaining buttons invisible
btnFbGetProfile.setVisibility(View.INVISIBLE);
btnPostToWall.setVisibility(View.INVISIBLE);
btnShowAccessTokens.setVisibility(View.INVISIBLE);
Logout.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) {
}
});
}
I found the Solution for my Question
i replaced my Facebook SDK 3.0 to 3.2 .
also changed the code for facebook login.
now Logout and Login Working fine.
MainActivity.java
public class MainActivity extends FragmentActivity {
String TAG="MainActivity";
private static final String PERMISSION = "publish_actions";
//private static final String PERMISSION = "email";
private final String PENDING_ACTION_BUNDLE_KEY = "pending_action";
private Button postStatusUpdateButton;
private LoginButton loginButton;
private ProfilePictureView profilePictureView;
private TextView greeting;
private PendingAction pendingAction = PendingAction.NONE;
private GraphUser user;
private GraphPlace place;
private List<GraphUser> tags;
private boolean canPresentShareDialog;
Button LogoutButton,Pro;
/* private static final List<String> PERMISSION = Arrays.asList(
"email","publish_actions");*/
private enum PendingAction
{
NONE, POST_STATUS_UPDATE
}
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception)
{
onSessionStateChange(session, state, exception);
}
};
private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
#Override
public void onError(FacebookDialog.PendingCall pendingCall,
Exception error, Bundle data) {
Log.d(TAG, String.format("Error: %s", error.toString()));
}
#Override
public void onComplete(FacebookDialog.PendingCall pendingCall,
Bundle data) {
Log.d(TAG, "Success!");
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
// Can we present the share dialog for regular links?
canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,FacebookDialog.ShareDialogFeature.SHARE_DIALOG);
if (savedInstanceState != null) {
String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
pendingAction = PendingAction.valueOf(name);
}
setContentView(R.layout.activity_main);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback()
{
#Override
public void onUserInfoFetched(GraphUser user)
{
MainActivity.this.user = user;
updateUI();
// It's possible that we were waiting for this.user to
// be populated in order to post a status update.
handlePendingAction();
}
});
profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
greeting = (TextView) findViewById(R.id.greeting);
postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
performPublish(PendingAction.POST_STATUS_UPDATE,canPresentShareDialog);
}
});
LogoutButton=(Button)findViewById(R.id.LogoutButton);
LogoutButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//callFacebookLogout(session);
Logout();
}
});
}
//override lifecycle methods so that UiLifecycleHelper know about state of the activity
#Override
protected void onResume() {
super.onResume();
uiHelper.onResume();
updateUI();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
private void onSessionStateChange(Session session, SessionState state,Exception exception)
{
if (state.isOpened()) {
Toast.makeText(getApplicationContext(), "User logged in...", Toast.LENGTH_SHORT).show();
getUserData(session,state);
} else if (state.isClosed()) {
Toast.makeText(getApplicationContext(), "User logged out...", Toast.LENGTH_SHORT).show();
}
if (pendingAction != PendingAction.NONE
&& (exception instanceof FacebookOperationCanceledException
|| exception instanceof FacebookAuthorizationException)) {
new AlertDialog.Builder(MainActivity.this)//if permission is not granted
.setTitle(R.string.cancelled)
.setMessage(R.string.permission_not_granted)
.setPositiveButton(R.string.ok, null).show();
pendingAction = PendingAction.NONE;
} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
handlePendingAction();
}
updateUI();
}
private void updateUI()
{
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
postStatusUpdateButton.setEnabled(enableButtons
|| canPresentShareDialog);
if (enableButtons && user != null)
{
profilePictureView.setProfileId(user.getId());
greeting.setText(getString(R.string.hello_user, user.getFirstName()));
} else {
profilePictureView.setProfileId(null);
greeting.setText(null);
}
}
#SuppressWarnings("incomplete-switch")
private void handlePendingAction() {
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but we assume they
// will succeed.
pendingAction = PendingAction.NONE;
switch (previouslyPendingAction) {
case POST_STATUS_UPDATE:
postStatusUpdate();
break;
}
}
private interface GraphObjectWithId extends GraphObject {
String getId();
}
private void showPublishResult(String message, GraphObject result,
FacebookRequestError error) {
String title = null;
String alertMessage = null;
if (error == null) {
title = getString(R.string.success);
String id = result.cast(GraphObjectWithId.class).getId();
alertMessage = getString(R.string.successfully_posted_post,
message, id);
} else {
title = getString(R.string.error);
alertMessage = error.getErrorMessage();
}
new AlertDialog.Builder(this).setTitle(title).setMessage(alertMessage)
.setPositiveButton(R.string.ok, null).show();
}
// create sample post to update on facebook
private FacebookDialog.ShareDialogBuilder createShareDialogBuilderForLink() {
return new FacebookDialog.ShareDialogBuilder(this)
.setName("Hello Facebook")
.setDescription("this is sample post from androidSRC.net to demonstrate facebook login in your android application")
.setLink("http://androidsrc.net/");
}
private void postStatusUpdate() {
if (canPresentShareDialog) {
FacebookDialog shareDialog = createShareDialogBuilderForLink().build();
uiHelper.trackPendingDialogCall(shareDialog.present());
} else if (user != null && hasPublishPermission()) {
final String message = getString(R.string.status_update,
user.getFirstName(), (new Date().toString()));
Request request = Request.newStatusUpdateRequest(
Session.getActiveSession(), message, place, tags,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(message,
response.getGraphObject(),
response.getError());
}
});
request.executeAsync();
} else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}
//check if app has permission to publish on facebook
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions")&&session.getPermissions().contains("email");
}
private void performPublish(PendingAction action, boolean allowNoSession) {
Session session = Session.getActiveSession();
if (session != null) {
pendingAction = action;
if (hasPublishPermission()) {
// We can do the action right away.
handlePendingAction();
return;
} else if (session.isOpened()) {
// We need to get new permissions, then complete the action when
// we get called back.
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSION));
return;
}
}
if (allowNoSession) {
pendingAction = action;
handlePendingAction();
}
}
public void Logout()
{
if (Session.getActiveSession() != null)
{
Session.getActiveSession().closeAndClearTokenInformation();
Toast.makeText(getApplicationContext(), "logged out...", Toast.LENGTH_SHORT).show();
}
Session.setActiveSession(null);
}
private void getUserData(Session session, SessionState state)
{
if (state.isOpened())
{
Request.newMeRequest(session, new Request.GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user, Response response)
{
if (response != null)
{
try
{
String name = user.getName();
// If you asked for email permission
String email = (String) user.getProperty("email");
// Log.e(LOG_TAG, "Name: " + name + " Email: " + email);
Toast.makeText(getApplicationContext(), "Name: " + name + " Email: " + email, Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
e.printStackTrace();
//Log.d(LOG_TAG, "Exception e");
}
}
}
}).executeAsync();
}
}
My logout Method
public void Logout()
{
if (Session.getActiveSession() != null)
{
Session.getActiveSession().closeAndClearTokenInformation();
Toast.makeText(getApplicationContext(), "logged out...", Toast.LENGTH_SHORT).show();
}
Session.setActiveSession(null);
}
Link i reffered
link
If you are using latest facebook sdk 4.0 then
LoginManager.getInstance().logOut();
Will work.
dependencies {
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
}

how to clear the session and token of facebook id,so as to login again

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

can login through one account only,it is not taking another id for login in facebook

in my application,i can loging through my facebook id.,it i enter another id,it didnot fetch data,as it do for my id.i can't understand what is the problem.when i enter another id,it showing loading,and after that onle blank facebook page is visible.
MainActivity
public class MainActivity extends Activity {
Facebook fb;
Button login,getData,logout;
ImageView ig;
String app_id;
private 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()){
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);
String access_token = mPrefs.getString("access_token", null);
long 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(getApplication(), "already login", Toast.LENGTH_LONG).show();
//logoutFromFacebook();
}
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) {
}
});
}
I had the same problem. I fixed it like this.
Go to Facebook developers page
Apps --> "YourApp" --> Status and Review --> Enable ("Do you want to make this app and all its live features available to the general public?")
Like this
When you create app on Facebook. You might have testing and enabled sandbox mode as shown in image.you need to disable it.
Note: don't look at other settings.it is app for web,similarly you will have sandbox option for mobile app.
Your code is not updated for latest Facebook SDK 3.8, now Facebook provide Default class for Login, Share, Import Photo from Facebook and much more. Please follow this link
https://developers.facebook.com/docs/android/login-with-facebook/

Facebook Login Issue in android

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.

Android facebook graph request

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

Categories

Resources