Search code examples
androidfirebasekotlinfirebase-authenticationkotlin-null-safety

How to avoid KotlinNullPointerException when creating a new User object?


I have this authentication code in Firebase:

auth.signInWithCredential(credential).addOnCompleteListener { task ->
    if (task.isSuccessful) {
        val firebaseUser = auth.currentUser!!
        val user = User(firebaseUser.uid, firebaseUser.displayName!!) //KotlinNullPointerException
    } 
}

This my User class:

data class User constructor(var uid: String? = null): Serializable {
    var name: String? = null

    constructor(uid: String, name: String) : this(uid) {
        this.name = name
    }
}

And I'm getting a KotlinNullPointerException at the highlighted line. How can the call of the constructor produce this exception? How can I avoid it?


Solution

  • Just declare your class like:

    data class User(var uid: String? = null, var name: String? = null) : Serializable
    

    And then you can call it like:

    auth.signInWithCredential(credential).addOnCompleteListener { task ->
        if (task.isSuccessful) {
            auth.currentUser?.apply {  // safe call operator, calls given block when currentUser is not null
                val user = User(uid, displayName)
            }
        } 
    }
    

    It is possible to create instance of User like this:

    User() // defaults to null as specified
    User("id") // only id is set, name is null
    User(name = "test-name") // only name is set id is null
    

    The = null exactly allows the invokation to pass the parameter optionally, when not passed defaulting to null.

    Edit: As suggested by @GastónSaillén, you should use Parcelable in Android.

    @Parcelize
    data class User(var uid: String? = null, var name: String? = null) : Parcelable