【问题标题】:Android Studio Kotlin Null Pointer Exception while updating Firestore Database更新 Firestore 数据库时 Android Studio Kotlin 空指针异常
【发布时间】:2021-12-27 01:39:52
【问题描述】:

我最近偶然发现了一个运行时错误,该错误导致我的应用程序由于某种原因而崩溃,我无法深入了解它。基本上,我通过将用户配置文件数据存储在哈希图中来更新它。这是用户类的样子:

@Parcelize
data class User(
    val id: String = "",
    val firstName: String = "",
    val lastName: String = "",
    val email: String = "",
    val image: String = "",
    val mobile: Long = 0,
    val gender: String = "",
    val profileCompleted: Int = 0): Parcelable

在我称为 UserProfileActivity 的活动中,我将手机和性别存储到哈希图中,然后调用 Firebase 函数来更新 Firestore 数据库。这是活动的方法。单击“提交”按钮时,此代码运行:

btn_submit.setOnClickListener {
            if(validateUserProfileDetails()){  //checks if entered credentials are valid
                val userHashMap = HashMap<String, Any>()  //creates the hashmap

                val mobileNumber = et_mobile_number.text.toString().trim { it <= ' ' }

                val gender = if (rb_male.isChecked) {  //these are radio buttons, only 1 clicked
                    Constants.MALE
                } else {
                    Constants.FEMALE
                }

                userHashMap[Constants.MOBILE] = mobileNumber.toLong()  //storing info in hashmap

                userHashMap[Constants.GENDER] = gender

                showProgressDialog(resources.getString(R.string.please_wait))  //starting a progress dialog

                FirestoreClass().updateUserProfileData(  //method in FirestoreClass 
                    this, userHashMap
                )
            }
        }

现在调用与数据库通信的方法:

fun updateUserProfileData(activity: Activity, userHashMap: HashMap<String, Any>) {
        mFireStore.collection(Constants.USERS)  // collection named "users"
            .document(getCurrentUserID())  //getCurrentUserID() just gets the current user id 
            .update(userHashMap)  // hashmap used to update the user
            .addOnSuccessListener {
                when (activity) {
                    is UserProfileActivity -> {
                        activity.userProfileUpdateSuccess() //this just hides the progress dialog and finishes the activity in the UserProfileActivity
                    }
                }
            }
            .addOnFailureListener { e ->
                when (activity) {
                    is UserProfileActivity -> {
                        activity.hideProgressDialog()
                    }
                }
            }


}

但我收到此错误:

2021-12-27 02:35:38.727 14960-14960/com.example.myshopapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myshopapp, PID: 14960
java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter it
    at com.example.myshopapp.firestore.FirestoreClass.updateUserProfileData$lambda-2(Unknown Source:7)
    at com.example.myshopapp.firestore.FirestoreClass.$r8$lambda$vs4EuaGwStcL-i3lXRUecduDHWM(Unknown Source:0)
    at com.example.myshopapp.firestore.FirestoreClass$$ExternalSyntheticLambda4.onSuccess(Unknown Source:4)
    at com.google.android.gms.tasks.zzm.run(com.google.android.gms:play-services-tasks@@18.0.0:1)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7656)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

我完全不知道空指针异常发生在哪里......而且有趣的是(这很重要),数据库确实得到了正确更新,为什么它会崩溃?任何帮助将非常感激。 :)

【问题讨论】:

  • 您应该首先使用调试器来跟踪代码并准确查看崩溃的位置。此外,为了发布到 Stack Overflow,您应该尽可能多地进行硬编码,并且不要让人们理所当然地认为您的所有变量和方法都按照您的想法行事。
  • 另外,无论是否相关,您都不应该将 Activity 实例向下传递到数据层,因为您将泄漏该对象并可能导致其他问题。

标签: android firebase kotlin google-cloud-firestore nullpointerexception


【解决方案1】:

这个特定错误最近经常出现,似乎是由于 Firebase 侦听器中的可空性注释不一致。

显然谷歌知道the issue和may have recently fixed it

当在 Kotlin 中为 update 调用添加 onSuccessListener 时,它会推断出 it 的非空类型(Void 不是 Void?)。这意味着如果 Firestore 返回 null 结果(这对于来自 java 的 Void 参数来说并不少见),它将引发您在将其强制转换为非 null 参数时显示的错误。解决方案是更新到修复此问题的最新版本,或者如果您需要立即解决方法来专门将类型设置为可为空,因此进行更改

.addOnSuccessListener { 
    println("Updated doc")
}

到

.addOnSuccessListener { _: Void? ->
    println("Updated doc")
}

【讨论】:

  • 遇到了同样的问题。您也可以使用OnCompleteListener 代替onSuccessListener stackoverflow.com/q/70568560/1621111
  • @KonstantinKonopko 没错,当我第一次遇到similar nullability issue 时,这也是我第一次在代码中使用的解决方案。它只是增加了一个额外的if( task.isSuccessful ) 行...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-11
  • 1970-01-01
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多