benb :
Im using Firebase Auth
in order to manage my login and register for the app.
I had like to add toast messages based on the exception that I receive.
For example, if the exception is from FirebaseAuthInvalidCredentialsException
I had like to toast one message. If it is from FirebaseAuthUserCollisionException
then I had like to use another toast.
I use something like:
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
LayoutInflater inflater = LayoutInflater.from( SignUpActivity.this );
View toastview = inflater.inflate( R.layout.toast_registered, null );
Toast toast = new Toast( SignUpActivity.this );
toast.setView( toastview );
toast.setGravity( Gravity.CENTER, 0, 3 );
toast.setDuration( Toast.LENGTH_LONG );
toast.show();
}
if (!task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, "toast1." + task.getException(),
Toast.LENGTH_SHORT).show();
}
if (!task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, "toast2." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(SignUpActivity.this, MainActivity.class));
finish();
}
}
});
So basically I need to add something to the if condition however im not sure what.
I saw a use of catch
but I dont think this is the situation.
Thank you
Thomas Cook :
This should do it:
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
LayoutInflater inflater = LayoutInflater.from( SignUpActivity.this );
View toastview = inflater.inflate( R.layout.toast_registered, null );
Toast toast = new Toast( SignUpActivity.this );
toast.setView( toastview );
toast.setGravity( Gravity.CENTER, 0, 3 );
toast.setDuration( Toast.LENGTH_LONG );
toast.show();
}
else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(SignUpActivity.this, "toast1." + task.getException(),
Toast.LENGTH_SHORT).show();
}
else if (task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(SignUpActivity.this, "toast2." + task.getException(),
Toast.LENGTH_SHORT).show();
}
startActivity(new Intent(SignUpActivity.this, MainActivity.class));
finish();
}
}
});
So, you check if task was successful, if not you switch on error type and show corresponding toast before starting signup activity and finishing this activity.