Home > database >  I do not get the error in the Logcat when a document of a user is not found in the collection but ap
I do not get the error in the Logcat when a document of a user is not found in the collection but ap

Time:11-02

I use Firebase PhoneAuth in my app and the following function is called after the verification is successfully finished. While I was doing some trial, I deleted the entire document of a user, who is authenticated using the phone number, from the collection called "users". Then when I try to open the app, the app crashes and gets java.lang.NullPointerException error. However, it doesn't show the error message for Log.d("Tag", e.message!!) in the .addOnFailureListener. How can I catch this type of error? Isn't .addOnFailureListener supposed to consider this as an error?

    fun getUserDetail(fragment: HomeFragment) {

    mFireStore.collection(Constants.USERS)
        .document(getCurrentUserID())
        .get()
        .addOnSuccessListener { document ->
            val user = document.toObject(User::class.java)!!
            fragment.successUserDetail(user)
        }
        .addOnFailureListener { e ->
            Log.d("Tag", e.message!!)
            fragment.hideProgressDialog()
        }
}

CodePudding user response:

You are getting that NullPointerException most likely at the following line of code:

 val user = document.toObject(User::class.java)!!

And it makes sense since you say you have deleted the user from the collection.

Isn't .addOnFailureListener supposed to consider this as an error?

No, that NPE is not a failure, it just indicates that you have called a method on a document that doesn't exist, in other words, which is null. However, a failure may occur when, for example, the Firebase servers reject your request due to improper security rules. I have also written an article regarding that called:

If you want to avoid that NPE, in a Kotlin style, you shouldn't use the !! operator but:

document?.let {
    val user = it.toObject(User::class.java)
    fragment.successUserDetail(user)
}
  • Related