我偶然发现了一个奇怪的问题。我正在尝试完成一个简单的事情-将所有内容从QuerySnapshot转换为某种类型的集合。

fun createReminder(reminder: Reminder) =
    remindersCollectionRef.document("${reminder.taskId}").set(reminder)

fun tryRemoveReminder(taskId: Int) =
    remindersCollectionRef.document("$taskId").delete()

fun getReminders(onComplete: (List<Reminder>) -> Unit) {
    remindersCollectionRef.get()
        .addOnSuccessListener { querySnapshot ->
            if (!querySnapshot.isEmpty)
                 onComplete(querySnapshot.toObjects(Reminder::class.java))
            }
        }

问题出在getReminders函数中。我知道集合中有一个提醒。它也是Reminder类型的100%,如您所见,我已经检查querySnapshot是否不为空。仍然,当我调用toObjects时,我仍然得到一个空指针异常。

堆栈跟踪:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Constructor.newInstance(java.lang.Object[])' on a null object reference
at com.google.android.gms.internal.zzevb$zza.zza(Unknown Source:57)
at com.google.android.gms.internal.zzevb.zza(Unknown Source:1025)
at com.google.android.gms.internal.zzevb.zza(Unknown Source:2)
at com.google.firebase.firestore.DocumentSnapshot.toObject(Unknown Source:10)
at com.google.firebase.firestore.QuerySnapshot.toObjects(Unknown Source:27)
at com.mypackage.util.FirestoreUtil$Companion$getReminders$1.onSuccess(FirestoreUtil.kt:131)
at com.mypackage.util.FirestoreUtil$Companion$getReminders$1.onSuccess(FirestoreUtil.kt:18)
at com.google.android.gms.tasks.zzj.run(Unknown Source:27)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)                                                                                      at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

提醒类:
data class Reminder(val taskDocRef: DocumentReference, val taskId: Int)

这个问题对我来说真的很奇怪。我将感谢您的帮助:)

最佳答案

如果您仔细阅读有关Cloud Firestore映射自定义对象here的查询要求的文档,将会注意到:

关于firebase - Cloud Firestore-QuerySnapshot.toObjects引发空指针异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48241124/

10-10 14:57