簡體   English   中英

Android Studio Kotlin Null 更新 Firestore 數據庫時出現指針異常

[英]Android Studio Kotlin Null Pointer Exception while updating Firestore Database

我最近偶然發現了一個運行時錯誤,無論出於何種原因導致我的應用程序崩潰,我無法深入了解它。 基本上,我通過將用戶配置文件數據存儲在 hashmap 中來更新它。 這是用戶 class 的樣子:

@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 的活動中,我將手機和性別存儲到 hashmap,然后調用 Firebase function 以更新 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)

我完全不知道 null 指針異常發生在哪里......而且有趣的是(這很重要),數據庫確實得到了正確更新,為什么它會崩潰? 任何幫助將非常感激。 :)

這個特定的錯誤最近出現了很多,似乎是由於 Firebase 偵聽器中的可空性注釋不一致。

addOnSuccessListener的簽名是(其中 TResult 對於文檔update調用是無效的):

@NonNull
public abstract Task<TResult> addOnSuccessListener(@NonNull OnSuccessListener<? super TResult> var1);

成功偵聽器的接口當前是(在提供的參數上沒有可空性注釋):

public interface OnSuccessListener<TResult> {
    void onSuccess(TResult var1);
}

但是,當在 Kotlin 中添加偵聽器時, it會為其推斷非空類型( Void not Void? )。 這意味着如果 Firestore 返回 null 結果(這對於來自 java 的Void參數並不少見),它將引發您在將其轉換為非空參數時顯示的錯誤。 解決方法是專門設置類型為nullable,所以要改

.addOnSuccessListener { 
    println("Updated doc")
}

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

相反, onFailureListener的接口是一個 Non-Null 非 void 參數,所以那里不應該有問題。

public interface OnFailureListener {
    void onFailure(@NonNull Exception var1);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM