Cloud Firestore中QuerySnapshot.toObjects调用抛出空指针异常求助
你遇到的空指针问题根源在于Firestore无法正确实例化你的Reminder数据类。从栈追踪能明显看到,异常发生在反射调用构造函数的环节——Firestore找不到合适的构造函数来创建Reminder实例,导致Constructor对象为null,进而触发了空指针异常。
问题分析
Kotlin的data class默认只会生成包含所有参数的主构造函数,而Firestore在反序列化Java/Kotlin对象时,需要满足以下条件之一:
- 类有一个无参构造函数(Firestore会先创建实例,再通过反射逐个设置字段值);
- 构造函数的参数名与Firestore文档中的字段名完全匹配(大小写敏感),且构造函数能被反射访问。
你的Reminder类既没有无参构造函数,若Firestore文档字段名和构造参数名不匹配,就会出现这个问题。
解决方案
这里有几种可行的修复方式,按推荐程度排序:
1. 给数据类参数添加默认值,自动生成无参构造函数
修改Reminder的定义,给每个参数设置默认值,Kotlin会自动生成无参构造函数,Firestore就能顺利实例化对象了:
import com.google.firebase.firestore.DocumentReference data class Reminder( val taskDocRef: DocumentReference? = null, val taskId: Int = 0 )
注:
DocumentReference是Firestore的引用类型,设置为可空并给默认值null是合理的,Firestore在反序列化时会自动填充正确的引用值。
2. 显式声明无参构造函数
如果你不想修改参数的可空性,可以显式添加一个无参构造函数:
import com.google.firebase.firestore.DocumentReference data class Reminder(val taskDocRef: DocumentReference, val taskId: Int) { // 显式无参构造函数,供Firestore实例化对象使用 constructor() : this(DocumentReference.forPath("dummy/path"), 0) }
这里用
DocumentReference.forPath创建临时空引用作为默认值,实际反序列化时Firestore会覆盖这个值。
3. 确保字段名完全匹配
检查Firestore文档中的字段名是否和Reminder的属性名完全一致(大小写敏感)。比如如果Firestore里的字段是task_doc_ref而非taskDocRef,需要用@PropertyName注解映射:
import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.PropertyName data class Reminder( @PropertyName("task_doc_ref") val taskDocRef: DocumentReference, @PropertyName("task_id") val taskId: Int ) { constructor() : this(DocumentReference.forPath("dummy/path"), 0) }
额外检查
- 确认
Reminder类是public的(Kotlin默认是internal,跨模块使用时需显式声明public); - 确保Firestore文档中的
taskDocRef字段确实是DocumentReference类型,而非字符串或其他类型,否则反序列化也会失败。
按照上面的方法修改后,querySnapshot.toObjects(Reminder::class.java)应该就能正常工作了。
内容的提问来源于stack exchange,提问作者Matt

