i'm trying to make an auth with facebook on firebase. I've already set up facebook SDK and I can sign in with facebook perfectly.
But I can't get firebase auth work. The app has a TOAST on the method onComplete(Task <AuthResult> task) and if something went wrong during the process it will show up. I'm getting this TOAST error, but can't find where is the problem. I've set up everything like in firebase docs.
public class LoginActivity extends AppCompatActivity {
private LoginButton loginButton;
private CallbackManager callbackManager;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener firebaseAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.loginButton);
loginButton.setReadPermissions("email","public_profile");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(),"Error al iniciar sesión",Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(),"Error al iniciar sesión",Toast.LENGTH_LONG).show();
}
});
firebaseAuthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
goMainScreen();
}
}
};
}
private void handleFacebookAccessToken(AccessToken accessToken) {
Log.d("","handle"+accessToken.getCurrentAccessToken().getToken());
AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getCurrentAccessToken().getToken());
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Toast.makeText(getApplicationContext(), "hi", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show(); // here is the ERROR.
}
}
});
}
private void goMainScreen() {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(firebaseAuthListener);
}
#Override
protected void onStop() {
super.onStop();
firebaseAuth.removeAuthStateListener(firebaseAuthListener);
}
}
I've already enabled Facebook auth on firebase and already copied the id and secret. Also I've already copied the Firebase URL in Facebook developers.
The task contains error information that may help you troubleshoot. Instead of showing "error" in your toast, show task.getException().toString() or better yet: throw the exception with throw task.getException().
Related
To my knowledge, all Facebook and Firebase connections are linked and all code should be functional. However, the authentication still isn't passing through Firebase, even though it is being logged on from Facebook.
My Code: ActMain.java
public class ActMain extends AppCompatActivity {
private FirebaseAuth fAuth;
/* Facebook */
private CallbackManager mCallbackManager;
private static final String TAG = ActMain.class.getSimpleName();
/* onCreate */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_act_main);
// Initialize Firebase Auth
fAuth = FirebaseAuth.getInstance();
// Initialize Facebook Login button
mCallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = findViewById(R.id.login_button);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
}
});
}
/* Facebook */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result back to the Facebook SDK
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void handleFacebookAccessToken(AccessToken token)
{
Log.d(TAG, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
fAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
{
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if (task.isSuccessful())
{
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = fAuth.getCurrentUser();
updateUI(user);
}
else
{
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(ActMain.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
I am totally lost on where to continue as it had worked before. Could I possibly be doing something very minor but due to that causing the authentication to fail?
Get the hashkey of your current package and put it on fb developer console.Then this will work.
I had the same error but the problem was that I am trying to login with same email on facebook & google so the email should be unique for each user.
I am using google firebase oAuth in my app for login
My problem is that everytime i open the app it ask to login .
I want to automate using token service but i dont know how to and what to do.
private static int RC_SIGN_IN = 0 ;
private static String TAG = "LOGIN_ACTIVITY";
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
Context context = LoginActivity.this;
public FirebaseAuth.AuthStateListener mAuthListener;
private EditText mEmailField,mPasswordField;
TextView register;
private String Email ;
Model_userDetails model_userDetails = new Model_userDetails(); ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
register = (TextView) findViewById(R.id.register);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user!=null) {
// new HttpCall().checkGoogleEmail(context, Email);
}
else
Log.d("AUTH","User logged out");
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build();
mGoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this,this).addApi(Auth.GOOGLE_SIGN_IN_API,gso).build();
findViewById(R.id.sign_in_button).setOnClickListener(this);
findViewById(R.id.email_sign_in_button).setOnClickListener(this);
mEmailField = (EditText) findViewById(R.id.email);
mPasswordField = (EditText) findViewById(R.id.password);
register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginActivity.this,NewUserActivity.class));
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if (mAuthListener !=null)
mAuth.removeAuthStateListener(mAuthListener);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==RC_SIGN_IN)
{
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess())
{
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
Email = mAuth.getCurrentUser().getEmail();
new HttpCall().checkGoogleEmail(context, Email);
}
else
Log.d(TAG,"Google login failed ");
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct){
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("AUTH","sign in with credentials: complete "+ task.isSuccessful());
}
});
}
private void signIn()
{
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent,RC_SIGN_IN);
}
private void emailSignIn()
{
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
if (TextUtils.isEmpty(email)|| TextUtils.isEmpty(password))
{
Toast.makeText(LoginActivity.this,"Fields are empty ",Toast.LENGTH_SHORT).show();
}
else
{
final ProgressDialog progressDialog = ProgressDialog.show(LoginActivity.this, "Please wait...", "Proccessing...", true);
(mAuth.signInWithEmailAndPassword(email,password))
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Login successful", Toast.LENGTH_LONG).show();
Intent i = new Intent(LoginActivity.this, AccountActivity.class);
i.putExtra("Email", mAuth.getCurrentUser().getEmail());
startActivity(i);
} else {
Log.e("ERROR", task.getException().toString());
Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG," Connection Failed");
}
This is my code
please help me with this
i got it myself . We have to call the new activity when checking if the user is login or not.
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user!=null) {
new HttpCall().checkGoogleEmail(context, Email);
}
else
Log.d("AUTH","User logged out");
}
};
I am using the facebook auth medthod with firebase and I can't figure out how to properly Log out a user. After I press the 'Continue with Facebook' button and give it access to my profile the button changes in 'Log out' and shows a dialog when I click it. The problem is that it doesn't actually log me out and the state is still signed in.
I found here how to log out the user from Firebase and Facebook in my app but I can't figure out where to put those 2 lines. I am looking for a Logout function or something like that.
I found here (different here) what might be my solution but it's pretty messy and can't understand. Can you please help me?
#Override
protected void onCreate(Bundle savedInstanceState) {
mAuth = FirebaseAuth.getInstance();
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
setContentView(R.layout.activity_login);
mCallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.e(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.e(TAG, "facebook:onCancel");
// ...
}
#Override
public void onError(FacebookException error) {
Log.e(TAG, "facebook:onError", error);
// ...
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.e(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
DatabaseReference myRef = database.getReference("Users");
myRef.addValueEventListener(new ValueEventListener() {
boolean userExists = false;
User userFirebase;
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot mydata : dataSnapshot.getChildren()){
userFirebase = mydata.getValue(User.class);
if(userFirebase.getEmail().equals(user.getEmail())){
Log.e(TAG, "User found in the database");
userExists = true;
Intent intent = new Intent(getBaseContext(), ActivityMain.class);
startActivity(intent);
break;
}
}
if (!userExists){
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("Users").push().setValue(new User(user.getDisplayName(),user.getEmail(),0,0));
Intent intent = new Intent(getBaseContext(), ActivityMain.class);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}); // checks if the user is in database and writes him if not
} else {
// User is signed out
Log.e(TAG, "onAuthStateChanged:signed_out");
}
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result back to the Facebook SDK
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void handleFacebookAccessToken(AccessToken token) {
Log.e(TAG, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.e(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.e(TAG, "signInWithCredential", task.getException());
Toast.makeText(getBaseContext(), "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
You need to implement your own button and add and OnClickListener with the 2 methods mentioned :
Button logoutButton = (Button) findViewById(R.id.logout_button);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
LoginManager.getInstance().logOut();
}
});
You can't use the facebook logout button , because it only logs you out of facebook and you need the firebase logout aswell.
We are implementing Firebase Facebook authentication for one of our projects. We have followed the steps mentioned in the documentation as well.
Here is the oAuth URL:
https://<APP_NAME>.firebaseapp.com/__/auth/handler
I've added the rest of the credentials as well (i.e the APP_ID & APP_SECRET), moreover the app is in development stage and I've added the key hash as well to the Facebook portal and Firebase portal.
The Login initial flow works well, but when the user confirm the permission to grant access, the callback register doesn't respond at all, neither with negative nor positive acknowledgement.
Here's our piece of code:
private static final String TAG = "FacebookLogin";
private CallbackManager mCallbackManager;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
// Initialize Facebook Login button
mCallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
// ...
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError"+ error);
// ...
}
});
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(FacebookLoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
Please let us know if we missed anything. I'm assuming there's something wrong about the callback URL, thus a bit more information on the same would be helpful as Firebase documentation doesn't clearly state about how to build up that URL. Thanks in advance.
Did you add
mCallbackManager.onActivityResult(requestCode, resultCode, data);
in your onActivityResult block?
Edit
Referring to the sample from Firebase https://github.com/firebase/quickstart-android/blob/master/auth/app/src/minSdkJellybean/java/com/google/firebase/quickstart/auth/FacebookLoginActivity.java,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
If this is not added, there would be no callback.
I am using the firebase documentation to use Facebook login my android application. I am successfully able to login users using Google and Twitter. But when i click on Login with Facebook, the button is changing to Logout button. Actually it should redirect to Login success activity, because i configured FirebaseAuth.AuthStateListener.
I am posting the Activity here, Please let me know if i am doing anything wrong.
public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "MainActivity";
private static final int GOOGLE_RC_SIGN_IN = 9001;
private static final int TWITTER_RC_SIGN_IN = 140;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private GoogleApiClient mGoogleApiClient;
CallbackManager callbackManager;
#BindView(R.id.google_signin_button) SignInButton mGoogleSigninButton;
#BindView(R.id.facebook_login_button) LoginButton mFacebookLoginButton;
#BindView(R.id.twitter_login_button) TwitterLoginButton mTwitterLoginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(getString(R.string.twitter_consumer_key), getString(R.string.twitter_consumer_secret));
Fabric.with(this, new Twitter(authConfig));
FacebookSdk.sdkInitialize(this);
setContentView(R.layout.activity_main);
ButterKnife.bind(MainActivity.this);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this,this)
.addApi(Auth.GOOGLE_SIGN_IN_API,gso)
.build();
mAuth = FirebaseAuth.getInstance();
mAuthStateListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
//User is signed in
Log.v(TAG, "Yo Baby");
Log.d(TAG,"name"+user.getDisplayName());
goToHome();
} else {
//Do some logic
}
}
};
mGoogleSigninButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent signinIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signinIntent, GOOGLE_RC_SIGN_IN);
}
});
callbackManager = CallbackManager.Factory.create();
mFacebookLoginButton.setReadPermissions("email", "public_profile");
mFacebookLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
handleFacebookAuthentication(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
mTwitterLoginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
handleTwitterAuthentication(result.data);
}
#Override
public void failure(TwitterException exception) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GOOGLE_RC_SIGN_IN){
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
handleGoogleAuthentication(account);
} else {
//Google Login Failed
}
} else if (requestCode == TWITTER_RC_SIGN_IN) {
mTwitterLoginButton.onActivityResult(requestCode,resultCode,data);
} else {
callbackManager.onActivityResult(requestCode,resultCode,data);
}
}
private void handleGoogleAuthentication(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//Save Credentials in Google Smart Lock
} else {
//
}
}
});
}
private void handleFacebookAuthentication(AccessToken accessToken) {
AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//Save Credentials in Google Smart Lock
} else {
}
}
});
}
private void handleTwitterAuthentication(TwitterSession session) {
AuthCredential credential = TwitterAuthProvider.getCredential(session.getAuthToken().token, session.getAuthToken().secret);
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//Save credentials in Google Smart lock
} else {
}
}
});
}
private void goToHome() {
startActivity(new Intent(MainActivity.this, HomeActivity.class));
finish();
return;
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onStop() {
super.onStop();
if (mAuthStateListener != null) {
mAuth.removeAuthStateListener(mAuthStateListener);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Update1
Finally I understood the reason why Facebook login is not working. This is because i already logged into the app using Google Signin. Since my email for Google and Facebook are same it is giving FirebaseAuthUserCollisionException. I should have Debugged the application before i post the question in Stackoverflow.
Update2
I am not closing this question as it may help someone who faced the situation like me. And I will also update the solution for FirebaseAuthUserCollisionException, as i dig more into it.
I faced the same problem and this is how I got around with.
If the task is not successful, I'm checking whether the exception thrown is an instanceof FirebaseAuthUserCollisionException. If yes, a toast is displayed to the user saying 'Account with email already exists!'.
private void handleFacebookAccessToken(final AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(getApplicationContext(), "Firebase Facebook login failed",
Toast.LENGTH_SHORT).show();
if(task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(getApplicationContext(), "User with Email id already exists",
Toast.LENGTH_SHORT).show();
}
LoginManager.getInstance().logOut();
}
}
});
}
Credit: Check if given email exists
About FirebaseAuthUserCollisionException:
https://developers.google.com/android/reference/com/google/firebase/auth/FirebaseAuthUserCollisionException
Preventing users from creating multiple accounts using the same email address with different authentication providers.
see https://support.google.com/firebase/answer/6400716