Hy, I'm trying to make a login on firebase using google SignIn. My problem is that when i'm gooing to connect, the application doesn't show me the email menu with all the email available and it do the connection without give the possibility to set more than one account.
I post my code below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btn_Sign = (SignInButton) findViewById(R.id.sign);
mAuth = FirebaseAuth.getInstance();
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
GoogleSignInOptions SignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, SignInOptions).build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
Btn_Sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CODE) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
}
}
}
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) {
if (task.isSuccessful()) {
Intent start = new Intent(MainActivity.this, Main2Activity.class);
startActivity(start);
} else {
Log.e(TAG, "signInWithCredential:failure", task.getException());
}
}
});
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
Thanks for the answers.
If you want to have always the dialog showing you need to disconnect your user before sign in
You can do it with this code
GoogleSignIn.getClient(getActivity(), GoogleSignInUser.getGoogleSignInOptions(getActivity())).signOut()
.addOnCompleteListener(getActivity(), new OnCompleteListener<Void>() {
#Override
public void onComplete(#android.support.annotation.NonNull Task<Void> task) {
GoogleSignIn.getClient(getActivity(), GoogleSignInUser.getGoogleSignInOptions(getActivity())).revokeAccess()
.addOnCompleteListener(getActivity(), new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//do what you want
}
})
.addOnCanceledListener(new OnCanceledListener() {
#Override
public void onCanceled() {
//do what you want
}
});
}
});
Related
i have a login activity,when user succes login from facebook it will go to mainactivity but it's keep coming back to login activity,pleaase help!!
this is my Login activity code i don't know what is wrong
i follow tutorial from this video https://www.youtube.com/watch?v=mapLbSKNc6I&t=1413s
i already try many thing's to fix this but it's not working
i hope someone will help me :)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
tvRegister = findViewById(R.id.btn_daftar);
email_et = findViewById(R.id.emailET);
password_et = findViewById(R.id.passwordET);
callbackManager = CallbackManager.Factory.create();
mAuth = FirebaseAuth.getInstance();
btn_masuk = findViewById(R.id.btn_masuk);
fbLogin = (Button) findViewById(R.id.facebookLogin);
fbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions(Login.this, Arrays.asList("email", "public_profile"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG,"facebook:onSucces:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG,"facebook:onCancel");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG,"facebook:onError");
}
});
}
});
btn_google_login = findViewById(R.id.google_login);
btn_google_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.google_login:
signIn();
break;
// ...
}
}
});
GoogleSignInOptions gso = new GoogleSignInOptions
.Builder()
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
btn_masuk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
email_txt = email_et.getText().toString();
password_txt = password_et.getText().toString();
if (TextUtils.isEmpty(email_txt)) {
Toast.makeText(getApplicationContext(), "Masukan Email !!!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password_txt)) {
Toast.makeText(getApplicationContext(), "Masukan Password !!!", Toast.LENGTH_SHORT).show();
return;
}
mAuth.signInWithEmailAndPassword(email_txt, password_txt)
.addOnCompleteListener(Login.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
Intent myIntent = new Intent(Login.this, IntroActivity.class);
Login.this.startActivity(myIntent);
finish();
} else {
Toast.makeText(Login.this, "Proses Login gagal : " + task.getException(),
Toast.LENGTH_LONG).show();
}
}
});
}
});
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
startActivity(new Intent(Login.this, MainActivity.class));
}
tvRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(Login.this, Register.class));
finish();
}
});
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
Log.d("TAG", "firebaseAuthWithGoogle: " + account.getId());
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()) {
Log.d("TAG", "Sign In Sukses");
FirebaseUser user = mAuth.getCurrentUser();
} else {
Log.d("TAG", "Sign In Gagagl");
Toast.makeText(Login.this, "SignIn Gagal!", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
if (requestCode == GOOGLE_SIGN) {
Task<GoogleSignInAccount> task = GoogleSignIn
.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
Intent myIntent = new Intent(Login.this, IntroActivity.class);
Login.this.startActivity(myIntent);
if (account != null) firebaseAuthWithGoogle(account);
} catch (ApiException e) {
e.printStackTrace();
}
}
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, GOOGLE_SIGN);
}
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) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
fbLogin.setEnabled(true);
updateUI();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(Login.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
fbLogin.setEnabled(false);
updateUI();
}
// ...
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser != null){
updateUI();
}
}
private void updateUI(){
Toast.makeText(Login.this,"Berhasil Login!", Toast.LENGTH_LONG).show();
Intent intenkuy = new Intent(Login.this,MainActivity.class);
startActivity(intenkuy);
finish();
}
}
I'm trying to do a authentication with firebase that only allows login to previously created users and I want to do it using google. Firebase provides the Google Sign-in but it creates the user if it doesn't exist.
There is a way to modify the code to allow only Login registered users ? If not, can you advice me to create a similar login ?
Login.java
public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient googleApiClient;
private SignInButton signInButton;
public static final int SIGN_IN_CODE = 777;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener firebaseAuthListener;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
signInButton = (SignInButton) findViewById(R.id.entrar);
signInButton.setSize(SignInButton.SIZE_WIDE);
signInButton.setColorScheme(SignInButton.COLOR_DARK);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intent, SIGN_IN_CODE);
}
});
firebaseAuth = FirebaseAuth.getInstance();
firebaseAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
goMainScreen();
}
}
};
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
#Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(firebaseAuthListener);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SIGN_IN_CODE) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
private void handleSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
firebaseAuthWithGoogle(result.getSignInAccount());
} else {
Toast.makeText(this, "NO S'HA POGUT CONNECTAR", Toast.LENGTH_SHORT).show();
}
}
private void firebaseAuthWithGoogle(final GoogleSignInAccount signInAccount) {
progressBar.setVisibility(View.VISIBLE);
signInButton.setVisibility(View.GONE);
AuthCredential credential = GoogleAuthProvider.getCredential(signInAccount.getIdToken(), null);
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
signInButton.setVisibility(View.VISIBLE);
if (!task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "NO S'HA POGUT AUTENTIFICAR", Toast.LENGTH_SHORT).show();
}
}
});
}
private void goMainScreen() {
Intent intent = new Intent(this, MainMenu.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
protected void onStop() {
super.onStop();
if (firebaseAuthListener != null) {
firebaseAuth.removeAuthStateListener(firebaseAuthListener);
}
}
}
Here is my error screenshotHello I am trying to login with Google and Facebook but it gives error.
com.google.firebase.auth.FirebaseAuthException: This operation is not allowed. You must enable this service in the console. How to solve this error? Do I have also enable the services on firebase how to solve this problem?
here is my code
public class LoginActivity extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener {
private Button btn_sign_up_login, btn_login, btn_gmail_login, btn_facebook_login;
private ProgressBar pb_sign_up_login, pb_login;
private FirebaseAuth.AuthStateListener mAuththenticatelistner;
private GoogleApiClient mGoogleapiclient;
public static final int RC_GOOGLE_LOGIN = 1;
private FirebaseAuth mAuth;
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_sign_up_login = (Button) findViewById(R.id.btn_sign_up_login);
callbackManager = CallbackManager.Factory.create();
btn_login = (Button) findViewById(R.id.btn_login);
btn_gmail_login = (Button) findViewById(R.id.btn_gmail_login);
btn_facebook_login = (Button) findViewById(R.id.btn_facebook_login);
pb_login = (ProgressBar) findViewById(R.id.pb_login);
///////////////////////////code for facebook login
// Initialize Facebook Login button
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.btn_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
handleFacebookAccessTokens(loginResult.getAccessToken());
}
#Override
public void onCancel() {
// [START_EXCLUDE]
updateUI(null);
// [END_EXCLUDE]
}
#Override
public void onError(FacebookException error) {
// [START_EXCLUDE]
updateUI(null);
// [END_EXCLUDE]
}
});
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.web_api_client_id))
.requestEmail()
.build();
mGoogleapiclient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
mAuth = FirebaseAuth.getInstance();
btn_sign_up_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
}
});
btn_gmail_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
btn_facebook_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleapiclient);
startActivityForResult(signInIntent, RC_GOOGLE_LOGIN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_GOOGLE_LOGIN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
// ...
}
}
}
// [START auth_with_google]
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) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
startActivity(new Intent(LoginActivity.this, DrawerActivity.class));
finish();
} else {
// If sign in fails, display a message to the user.
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
}
#Override
public void onClick(View view) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
private void updateUI(FirebaseUser user) {
if (user != null) {
String mailid = (getString(R.string.google_status_fmt, user.getEmail()));
String idfor = (getString(R.string.firebase_status_fmt, user.getUid()));
} else {
}
}
// [START auth_with_facebook]
private void handleFacebookAccessTokens(AccessToken token) {
// [END_EXCLUDE]
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()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// [START_EXCLUDE]
// [END_EXCLUDE]
}
});
}
// [END auth_with_facebook]
}
As the error states, you need to enable the authentication methods in the Firebase console. Navigate to Authentication>Sign-In Method and enable the required methods.
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 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