javaandroidfirebasefirebase-authenticationclasscastexception

java.lang.ClassCastException: com.google.firebase.FirebaseException cannot be cast to com.google.firebase.auth.FirebaseAuthException


Whenever I am trying to get the errorCode from the exception received from task.getException() by typecasting to "FirebaseAuthException" it gives and error as java.lang.ClassCastException: com.google.firebase.FirebaseException cannot be cast to com.google.firebase.auth.FirebaseAuthException and it always returns "An Error has occurred [INVALID_LOGIN_CREDENTIALS]" by the getMessage method task.getException().getMessage();

Here is the code which is causing the error.

String errorCode = ((FirebaseAuthException) task.getException()).getErrorCode();

I have provided invalid credentials just to get the exception, but I am not getting the exact exception like if the password is wrong the email is incorrect, or user is not found, etc.

I am using Android Studio Giraffe, 2022.3.1 Patch 2

Here are the dependencies I am using

implementation("com.google.firebase:firebase-auth:22.1.2")
implementation("com.google.firebase:firebase-database:20.2.2")
implementation("com.google.firebase:firebase-storage:20.2.1")

Solution

  • When you're using the following line of code:

    String errorCode = ((FirebaseAuthException) task.getException()).getErrorCode();
    

    The type of object that is returned by task.getException() is FirebaseException. Trying to cast such an object to an object of type FirebaseAuthException will indeed produce the following error:

    java.lang.ClassCastException: com.google.firebase.FirebaseException cannot be cast to com.google.firebase.auth.FirebaseAuthException

    Why? Because you cannot cast an object of a super-class into an object of a sub-class. Please note that the inheritance relationship is FirebaseAuthException extends FirebaseException and not vice versa. Where the FirebaseException class is the super-class, while the FirebaseAuthException is the sub-class.

    Please also note that a FirebaseAuthException is thrown only if signing in via the startActivityForSignInWithProvider method has been disabled in the Firebase Console, or if the provider passed is configured improperly.

    If you want to get more details about the Exception, then you should consider calling getCause(), getMessage(), or printStackTrace().

    Edit:

    When it comes to errors like this:

    INVALID_LOGIN_CREDENTIALS

    Then please also see the answer below: