Reputation: 1352
I just created SignIn(AppCompatActivity activity, String email, String password)
method to login existing users in my Firebase Android app. It works perfect with correct credentials, but when incorrect email and/or password entered it cannot catch proper exception. Here is the method:
public static int SignIn(final AppCompatActivity activity, String email, String password) {
int resultTask = -2;
FirebaseUtil.mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(activity, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
if (!FirebaseUtil.mAuth.getCurrentUser().isEmailVerified()) {
FirebaseUtil.mAuth.getCurrentUser().sendEmailVerification();
FirebaseUtil.mAuth.signOut();
resultTask = 1;
} else {
FirebaseUtil.isCustom = true;
resultTask = 2;
}
} else
resultTask = -1;
}
});
return resultTask;
}
It returns -2, when wrong credentials entered. What is going wrong with the method?
I solved the problem by changing method type from int
to void
. Here is why:
In my activity/fragment I called the method like,
int result = SignInUpActivity(_params_);
Give attention to default return value of the method (it is -2 but after execution of Firebase operations like sign in/up it could return any other value).
After this line I check for the result
:
if (result == -2) {
// some stuff
}
else if (result == -1) {
// some other stuff
}
else if (result == 0) {
// ...
}
// and other value checks for result handling
At this time, I did not give a time to Firebase to fetch/check/perform its own methods for authentication. Thus, SignInUpActivity()
returns its default value (-2). To completely remove the headache, I changed the method type from int
to void
.
My final code looks like this:
public static void SignIn(final AppCompatActivity activity, final String email, final String password) {
FirebaseUtil.mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
/**
* Thrown when one or more of the credentials passed to a method fail to
* identify and/or authenticate the user subject of that operation.
* Inspect the error code and message to find out the specific cause.
* https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuthInvalidCredentialsException
*/
ProgressDialog.DismissProgressDialog();
AlertDialog.ShowAlertDialog(activity,
"Invalid credentials", "Check email and password again.",
true, "ok", null,
false, "", null,
false, -1,
true);
} else if (task.getException() instanceof FirebaseAuthInvalidUserException) {
/**
* Inspect the error code and message to find out the specific cause.
* https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuthInvalidUserException
*/
ProgressDialog.DismissProgressDialog();
AlertDialog.ShowAlertDialog(activity,
"Invalid credentials", "Check email and password again.",
true, "ok", null,
false, "", null,
false, -1,
true);
}
} else {
if (!FirebaseUtil.mAuth.getCurrentUser().isEmailVerified()) {
FirebaseUtil.mAuth.getCurrentUser().sendEmailVerification();
FirebaseUtil.mAuth.signOut();
ProgressDialog.DismissProgressDialog();
AlertDialog.ShowAlertDialog(activity,
"Email not verified", "To start working, please verify your email.",
true, "ok", null,
false, "", null,
true, R.drawable.ic_verified_user,
true);
} else {
FirebaseUtil.isCustom = true;
ProgressDialog.DismissProgressDialog();
}
}
}
});
}
public static void Register(final AppCompatActivity activity, final String email, final String password) {
FirebaseUtil.mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
/**
* Thrown when an operation on a FirebaseUser instance couldn't be
* completed due to a conflict with another existing user.
* https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuthUserCollisionException
*/
ProgressDialog.DismissProgressDialog();
AlertDialog.ShowAlertDialog(activity,
"Try another", "This email has already registered.",
true, "ok", null,
false, "", null,
false, -1,
true);
} else {
ProgressDialog.DismissProgressDialog();
AlertDialog.ShowAlertDialog(activity,
"Whoops", "An error occurred. Try again later.",
true, "ok", null,
false, "", null,
false, -1,
true);
}
} else {
try {
FirebaseUtil.mAuth.getCurrentUser().sendEmailVerification();
FirebaseUtil.mAuth.signOut();
ProgressDialog.DismissProgressDialog();
AlertDialog.ShowAlertDialog(activity,
"The last step", "For verification, instructions sent to your email. Please, check your email.",
true, "ok", null,
false, "", null,
true, R.drawable.ic_verified_user,
true);
} catch (Exception e) {
ProgressDialog.DismissProgressDialog();
AlertDialog.ShowAlertDialog(activity,
"Whoops", "An error occurred. Try again later.",
true, "ok", null,
false, "", null,
false, -1,
true);
}
}
}
});
}
Anyway, problem solved.
Upvotes: 2
Views: 2403
Reputation: 393
You are not getting any exception because you are not catching exception in onComplete() . Read this code for your reference. here mAuth = FirebaseAuth.getInstance();
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
// If task is successful write method which you wan to do .
Log.d(LOG_TAG, "signIn With Email:onComplete");
// If signin 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 is unsuccessful then catch exception
// following are the possible exception which can occurs in signInWithEmailAndPassword().
if (!task.isSuccessful()) {
try {
throw task.getException();
} catch (FirebaseAuthInvalidUserException e) {
// show error toast to user or do something
} catch (FirebaseAuthInvalidCredentialsException e) {
// show error toast to user or do something
} catch (FirebaseNetworkException e) {
// show error toast to user or do something
} catch (Exception e) {
Log.e(LOG_TAG, e.getMessage());
}
Log.w(LOG_TAG, "signInWithEmail:failed",task.getException());
}
}
});
Upvotes: 1
Reputation: 297
Your method will always returning -2 , because you set a listener to addOnCompleteListener
.
Setting a listener meaning that when the action is executing the code in the method onComplete
(for example )will execute.
In your case every time you call the function SignIn
it will set a new listener to addOnCompleteListener
, the right way for doing that is to make that code outside this function probably in the onCreate method, and every time the user trying to sign in any where in your code the code in the onComplete
method will called and executed.
Please avoid writing this way , It's better to make a new class of your listener, and call it like this FirebaseUtil.mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new Mylistener())
, sure you will need to implements the right interface for your Mylistener
to access the onComplete
method
EDIT :
Sure to perform this Sign in method you should call it like this :
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
Then when the method above execute and complete the onComplete method in your code will be executed.
Upvotes: 2
Reputation: 1126
According to this question:How to catch a Firebase Auth specific exceptions
you should check
if (!task.isSuccessful())
but instead you are doing
if (task.isSuccessful())
then you can throw the Exception returned by task.getException inside a try block and catch each type of Exception that may be thrown by the method you are using
Upvotes: 2