Ad

Kotlin Firebase OnFailureListener Null Exception

I am trying to update email of user in my android app. And everything works fine if the new email is available. When it isn't - onFailureListener is calling. But when I am trying to get the exception from this listener it is null and I can't get type of this exception. Why? Code below.

private fun reauthenticateAndUpdateEmail(password: String, newEmail: String){
    val credentials = EmailAuthProvider.getCredential(auth.currentUser!!.email!!, password)
    auth.currentUser!!.reauthenticate(credentials).addOnCompleteListener(object : OnCompleteListener<Void> {
        override fun onComplete(p0: Task<Void>) {
            if (p0.isSuccessful) {
                auth.currentUser!!.updateEmail(newEmail).addOnSuccessListener {
                    interractor.emailChanged()
                }.addOnFailureListener { exception ->
                    interractor.emailChanged(false, handleException(p0.exception))
                }
            } else interractor.emailChanged(false, handleException(p0.exception))
        }
    })
}

private fun handleException(exception: Exception?): String{
    //exception is null
    when(exception){
        is FirebaseAuthUserCollisionException -> return "E-mail address is not available"
        is FirebaseNetworkException -> return "No network"
        else -> return "Try again later."
    }
}

Thanks in advance and have a nice day.

Ad

Answer

Try replacing

.addOnFailureListener { exception ->
                    interractor.emailChanged(false, handleException(p0.exception))
                }

with

.addOnFailureListener { exception ->
                    interractor.emailChanged(false, handleException(exception))
                }

You could also safeguard your handleException method: Replace

    when(exception){
        is FirebaseAuthUserCollisionException -> return "E-mail address is not available"
        is FirebaseNetworkException -> return "No network"
        else -> return "Try again later."
    }

with

    exception?.let {
          when(it){
             is FirebaseAuthUserCollisionException -> return "E-mail address is not available"
             is FirebaseNetworkException -> return "No network"
             else -> return "Try again later."
          }
    }
return "Unknown error"
Ad
source: stackoverflow.com
Ad