I want to implement Facebook Login in my application, but here I am getting problem while trying to login i.e :
**{Session state:OPENING, token:{AccessToken token:ACCESS_TOKEN_REMOVED permissions:[]}, appId:1xxxxxxxxxxxxxxx}**
and sometimes this one also:
**{Session state:CLOSED, token:{AccessToken token:ACCESS_TOKEN_REMOVED permissions:[]}, appId:1xxxxxxxxxxxxxxx}**
Note: The above problem occurs when my device already has installed NATIVE FACEBOOK APP, if I uninstall the Facebook app it works absolutely fine. Can Anyone please help me out what the matter is ?
Thanks in advance
Be sure to override in your Activity the onActivityResult method:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
Try
AccessToken.getCurrentAccessToken().getToken();
instead of using the toString() function.
I know this is an old ticket, but no one has appeared to give the correct answer. The token is removed from toString to prevent token exposure.
com.facebook.LoggingBehavior (from line 29):
/**
* Indicates that access tokens should be logged as part of the request logging; normally they are not.
*/
INCLUDE_ACCESS_TOKENS,
com.facebook.AccessToken (from line 322):
private String tokenToString() {
if (this.token == null) {
return "null";
} else if (Settings.isLoggingBehaviorEnabled(LoggingBehavior.INCLUDE_ACCESS_TOKENS)) {
return this.token;
} else {
return "ACCESS_TOKEN_REMOVED";
}
}
To show the token in toString requests simply add logging to the settings :
Settings.addLoggingBehavior( LoggingBehavior.INCLUDE_ACCESS_TOKENS );
this.mUiLifecycleHelper = new UiLifecycleHelper( this, this.mCallback );
this.mUiLifecycleHelper.onCreate( savedInstanceState );
Hope this helps others with the same issue.
Just a heads up.
This exact case was happening to me. My login stopped working just because I changed my Activity launch mode in Manifest.xml file from:
android:launchMode="singleInstance"
to
android:launchMode="singleTask"
So, I changed it again to singleInstance and it is working fine now.
This maybe happening because you didn't add the hashkey in your Facebook app. Check out this link Generating Hashkey for Android to learn how to generate hashkey.
This was happening to me too. It started working after i added the hashkey in Facebook app.
This is my working integration of new Facebook SDK 4.1.
First you need to init SDKin 4.1 ///
/** if face book SDK is not initialized then initialized.*/
if(!FacebookSdk.isInitialized())
FacebookSdk.sdkInitialize(BaseActivity.this);
Now you need callback manger
/** create face book callback factory.*/
if(null == callbackManager)
callbackManager = CallbackManager.Factory.create();
These are call back.
public final FacebookCallback<LoginResult> _mcallbackLogin = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
if(loginResult.getAccessToken() != null){
Log.i("TAG", "LoginButton FacebookCallback onSuccess token : "+ loginResult.getAccessToken().getToken());
GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
if(null != object){
Log.e("TAG", object.optString("name"),object.optString("first_name"),object.optString("email"),false).execute();
}
}
}).executeAsync();
}
}
#Override
public void onCancel() {
Log.e("TAG", "LoginButton FacebookCallback onCancel");
}
#Override
public void onError(FacebookException exception) {
Log.e("TAG","Exception:: "+exception.getStackTrace());
}
};
Now you need register call back on facebook login button
loginBtn.registerCallback(BaseActivity.callbackManager,_mcallbackLogin);
Related
I have added facebook login to my app.
First time I am able to login without any issue. But after login and then I logout. I am getting this error in the logcat.
E/LoginFragment: Cannot call LoginFragment with a null calling package. This can occur if the launchMode of the caller is singleInstance.
I searched google a bit. Some errors were resolved by setting launchmode to standard. I didn't specify any launchmode. But still I tried with
<activity
android:name=".activities.LoginActivity"
android:launchMode="standard"/>
But got no success.
Here is my procedure to login.
1 Added FB dependency compile 'com.facebook.android:facebook-android-sdk:[4,5)'
2 I initialize FB sdk in Application Class's onCreate() After super.onCreate(). AppEventsLogger.activateApp(this);
3 In my login activity created CallbackManager instance on the onCreate() of activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_login);
}
4 I used a custom button to login. When I clicked on fb login button. I am using this code.
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
//My Stuff Here
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,first_name,last_name,link,picture.type(large)");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
//Cancel Stuff
}
#Override
public void onError(FacebookException exception) {
exception.printStackTrace();
//Error Stuff
}
}); LoginManager.getInstance().logInWithReadPermissions((AppCompatActivity)context,
Arrays.asList("public_profile, email"));
5 I registered for callbacks in onActivityResult()
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
6 And to logout I have used LoginManager.getInstance().logOut()
7 But I try to login again with my custom button, the debug pointer goes to the line LoginManager.getInstance().registerCallback() but none of the methods (onSuccess(LoginResult loginResult), onError(), onError(FacebookException exception)) of the callback gets call. And I get a log saying E/LoginFragment: Cannot call LoginFragment with a null calling package. This can occur if the launchMode of the caller is singleInstance.
Change this
LoginManager.getInstance().logInWithReadPermissions((AppCompatActivity)context,
Arrays.asList("public_profile, email"));
to
LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this,
Arrays.asList("public_profile, email"));
First of all, Facebook is not giving exact exception details here.
Answer of Sushobh Nadiger helped me get to the issue.
I wanted to isolate the facebook login code from my LoginActivity and return the JSONObject back to LoginActivity so I created a class for handling Social Login called SocialLogin.java and I registered the callback in SocialLogin.java via LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() { //More Stuff here } and called login for facebook LoginManager.getInstance().logInWithReadPermissions() for more details see the full code in question.
This was the actual issue. So I made these calls (registerCallback() and logInWithReadPermissions()) in my LoginActivity.java and it worked.
However I as developer would think that a company like facebook should give us proper error rather than like this misleading error in my case so that our precious time could not be wasted.
I have an Android app and I am trying to use Facebook's SDK (version 4.1.0) to get a token and log in. Here is my code:
public class LoginActivity extends Activity {
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Log.v(TAG, "Facebook login was successful");
String authToken = accessToken.getToken();
// User authToken here:
}
#Override
public void onCancel() {
Log.v(TAG, "Facebook login was canceled");
}
#Override
public void onError(FacebookException e) {
Log.e(TAG, "Facebook login failed: " + e.getMessage());
}
});
Button facebook_button = (Button) findViewById(R.id.fbButton);
facebook_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile"));
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
The code switched to the Facebook app and back and OnActivityResult() is called. However, every time the callback method that is called is onCancel(). Note that I am not using the LoginButton provided by Facebook, and I have my own button (although I tried that approach and the result was the same). I double and triple checked my app ID and the keyhash generated by the app and they look correct too. So, I don't know what else may be wrong. Any help at this point is greatly appreciated.
yes i was facing the same issue, resolved it by using the below code just before login
LoginManager.getInstance().logOut();
The reason behind this behaviour is that you are already logged in. So when you revoke it, oncancel() gets called instead of onsubmit(). So just perform logout on your application's logout button like this
Import -->
import com.facebook.login.LoginManager;
Implementation -->
LoginManager.getInstance().logOut();
I had the same issue, eventually I found the problem. The activity calling facebook login fragment had android:launchMode="singleInstance" in the manifest file.
#Override
public void onCancel() {
accessToken = AccessToken.getCurrentAccessToken();
if (accessToken == null) {
Toast.makeText(LoginActivity.this, "Login unSuccessful..Please contact developer... ", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, "Login Successful. ", Toast.LENGTH_LONG).show();
}
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "Login attempt failed.", Toast.LENGTH_SHORT).show();
}
List item
#Doru's comment lead me to the solution. I used the Facebook activity rather than fragment.
Instead of
<activity android:name="com.facebook.FacebookActivity"
android:screenOrientation="portrait"
android:launchMode="singleTask" />
I needed to write
<activity android:name="com.facebook.FacebookActivity"
android:screenOrientation="portrait" />
What's nasty about this bug, is that it only occurs on old Android versions (e.g. 4.4.2, not 5.0).
If anyone comes across this in the future, this can also be caused by the Facebook native app installed on the device blocking login due to reason X.
In my case, this was being thrown every single time I attempted login. I finally switched over to the native Facebook app and as it opened, it required authentication and had me log in again due to some 'suspicious activity' (I think I changed my number recently).
If you are doing everything that is listed above and users are still complaining about it (and they have the app installed, you can use the code at the bottom to see if the Facebook app in installed:) you may wish to include a dialog that asks them to check the Facebook app and make sure they are still logged in, which would then prompt them to fix any errors before tabbing back into your application.
//Code to check if Facebook app is installed:
public static boolean doesUserHaveFacebookAppInstalled(Context context){
try{
context.getPackageManager().getApplicationInfo("com.facebook.katana", 0 );
return true;
} catch( PackageManager.NameNotFoundException e ){
return false;
}
}
The issue was simply because the APP ID needed to be in double-quotes.
I have the following code. It is a simple test of the callback function of the LoginButton in Facebook's Android API.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.setReadPermissions("user_friends");
loginButton.setReadPermissions("email");
loginButton.setReadPermissions("public_profile");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.e("SUCCESS", "LOGIN SUCCESSFUL");
}
#Override
public void onCancel() {
Log.e("CANCEL", "Cancelled");
}
#Override
public void onError(FacebookException e) {
Log.e("ERROR", "Facebook Exception");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
The only problem is that whenever I click the loginButton, a dialog appears and disappears for a brief moment, and then the logcat prints out the "CANCEL" text. I cannot seem to fix this error, and I'm not clicking cancel, because that dialog simply shows up and immediately disappears.
Please help me fix this?
As Facebook now requires review of applications which use publish access, you need to log into Facebook Developers Console, in Apps section select your app, click on Roles and add tester (or admin) role.
After this you should be able to get proper access token.
This answer helped me in similar situation.
https://stackoverflow.com/a/31625256/1987045
Call LoginManager.getInstance().logOut(); before attempting a sign in.
I encountered this issue.
It seems to be the case that if you attempt to login (using logInWithReadPermissions or logInWithPublishPermissions) when you already have an access token (with all of the required permissions) then the onCancel callback is executed.
That is to say you should not be logging the user in because the user is already logged in. Check for this first.
My solution:
I had the same problem. The callback was always received by onCancel() method.
I was performing a native login (meaning I was using Facebook App), so after talking with a work-mate, I unistalled my Facebook App to check whether a non-native loging was possible and run my app. To my surprise, before receiving the callback on the onCancel() method, a message informed me my Facebook App ID was wrong, so that was all. I had copied a wrong one instead of the one you get from https://developers.facebook.com/apps.
Now it works and even displays the permissions dialog. What I mean with this is that always try native and non-native. Maybe you get the answer from any of them.
For me this happened because I was calling finish() on my Activity before the Facebook callbacks could complete, causing the activity to finish with RESULT_CANCELED instead of RESULT_OK.
More specifically, my buggy code looked something like this:
#Override
protected void onStart() {
super.onStart();
if (!mAuthRequested) {
mAuthRequested = true;
promptSignIn();
} else {
finish();
}
}
What was happening is that once Facebook's auth activity finishes, onStart() gets called again, but else { finish(); } is invoked before any of Facebook's callbacks are. The fix was to remove the else block.
I hope this helps someone!
I am using the Facebook SDK but I want to create the photo album but I am getting ACCESS_TOKEN_REMOVED in the session.
Getting this in session
{Session state:OPENED, token:{AccessToken token:ACCESS_TOKEN_REMOVED permissions:[read_stream, manage_friendlists, read_mailbox, status_update, photo_upload, video_upload, sms, create_event, rsvp_event, email, xmpp_login, create_note, share_item, publish_stream, ads_management, read_insights, read_requests, manage_notifications, read_friendlists, manage_pages, publish_actions, user_birthday, user_religion_politics, user_relationships, user_relationship_details, user_hometown, user_location, user_likes, user_activities, user_interests, user_education_history, user_work_history, user_online_presence, user_website, user_groups, user_events, user_photos, user_videos, user_photo_video_tags, user_notes, user_checkins, user_about_me, user_status, basic_info]}, appId:458921577539675}
Code.
/**
* Connect to facebook using Facebook SDK.
*/
public void connectToFacebook() {
Session session = Session.getActiveSession();
if(session == null || session.isClosed()) {
Session.openActiveSession((Activity)context, true, new StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if(session.isOpened() && state == SessionState.CREATED_TOKEN_LOADED) {
Log.v(GlobalVars.TAG, "Token::" + session.getAccessToken());
Request.executeMeRequestAsync(session, new GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if(response != null) {
Log.v(GlobalVars.TAG, "Response::" + response);
Log.v(GlobalVars.TAG, "Response::" + user.getFirstName() + ":::" + user.getLastName());
}
}
});
}
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
If you are just seeing ACCESS_TOKEN_REMOVED in your log, make sure you are printing session.getAccessToken().getToken(). In the example above, replace
Log.v(GlobalVars.TAG, "Token::" + session.getAccessToken());
with
Log.v(GlobalVars.TAG, "Token::" + session.getAccessToken().getToken());
Same problem that i was facing from last 2 days and finally i get to know this. Facebook SDK will not log access tokens to logcat (to avoid leaking user tokens via the log as said in decsription).
Just add these lines after FacebookSdk.sdkInitialize(), i would recomend you do this only in debug mode:
if (BuildConfig.DEBUG) {
FacebookSdk.setIsDebugEnabled(true);
FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
}
You have to enable facebook sign in on Firebase Console and add the facebook app id and app secret key and it should work fine
I took the same problem :/
You can check:
Is appId correct?
Was keyhash registered in facebook app center?
Does app namespace / package name match with your manifest file? ( on facebook app center )
Is application live?
If everything is right I really don't know how to help you...
I checked all items that Fernando said and add it
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
I don't know if this last line was what solved the problem or if it's something random.
I'm using Facebook Android SDK 3.17 for Xamarin
Greetings from Argentina
Hernan
www.hernanzaldivar.com
So I have a simple login button that does this in my oncreate:
mLoginButton = (LoginButton)findViewById(R.id.connect_facebook_button);
mLoginButton.setApplicationId(.getResources().getString(R.string.app_id));
mLoginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
public void onUserInfoFetched(GraphUser user) {
setUser(user); // Just sets mUser to be this user
try {
Toast.makeText(this, mUser.getFirstName(), Toast.LENGTH_SHORT).show();
} catch (Exception FacebookException) {
FacebookException.printStackTrace();
}
}
});
All of that is called successfully, including the onUserInfoFetched.
The problem is, in every instance, my Graphuser user is null.
My appID is correct, my android hash is the debug one that they give me (tested on sample apps worked fine), the login screen does actually pop up... Not really sure where to go from here.
Also, if I hit the button twice, I get an error:
an attempt was made to open a session that has a pending request
Whoops! Forgot my activity result!
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
That did the trick.