var notify = ArrayList<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_user)
btn_list2.setOnClickListener {
val sharedPreferences1 = getSharedPreferences("id", Context.MODE_PRIVATE)
val documentid: String? = sharedPreferences1.getString("id","null")
val c = FirebaseFirestore.getInstance()
val d = c.collection("applicationForm").document(documentid.toString()).get()
.addOnSuccessListener { document ->
notify = document?.get("notifyTo") as ArrayList<String>
var str1 = notify.joinToString()
Toast.makeText(applicationContext,str1,Toast.LENGTH_SHORT).show()
}}}这里我得到了行notify = document?.get("notifyTo") as ArrayList<String>中的错误。
这是我的日志细节
java.lang.NullPointerException: null cannot be cast to non-null type java.util.ArrayList<kotlin.String>
at com.example.bloodbankcompany.MainActivityUser.onCreate$lambda-4$lambda-3(MainActivityUser.kt:47)
at com.example.bloodbankcompany.MainActivityUser.lambda$cGlrfLFSOO25IeEAacXMuz6Tzx0(Unknown Source:0)`. 有人能帮忙吗。在这里,我试图从消防局读取一个数组文档。
发布于 2021-07-22 22:40:02
您正在正确地对document?.get(...)进行门控,但您正在将结果转换为ArrayList。
由于要么document为null,要么文档结果中没有"notifyTo"键,因此您最终基本上会执行null as ArrayList<String>。因此出现了错误。
要停止崩溃,您需要执行document.get("notifyTo") as? ArrayList<String>
但真正想要确保的是文档中存在"notifyTo“,以便不再获得空返回值。
发布于 2021-07-22 21:50:57
首先,.addOnSuccessListener返回结果,而不是值,因此它显然会导致异常。
var documents: ArrayList<String> = arrayListOf()
c.collection("applicationForm").document(documentid.toString()).get()
.addOnSuccessListener { result ->
documents = result.value
}还检查result.values是否为!= null,获取如下值,并在末尾检查是否正确地映射了集合。
https://stackoverflow.com/questions/68491774
复制相似问题