科特林"NullPointerException: null cannot be cast to non null type Error"



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)`. 

请任何人帮忙。在这里,我正试图从firestore中读取数组文档。

您正确地选通了document?.get(...),但将结果强制转换为ArrayList。

由于document为空,或者文档结果中没有"notifyTo"键,所以最终基本上是执行null as ArrayList<String>。因此出现了错误。

要停止崩溃,您需要执行document.get("notifyTo") as? ArrayList<String>

但你真正想确保的是";notifyTo";存在于您的文档中,因此您不再获得空返回值

首先,.addOnSuccessListener返回的是结果,而不是值,因此它显然会导致异常。

var documents: ArrayList<String> = arrayListOf()
c.collection("applicationForm").document(documentid.toString()).get()
.addOnSuccessListener { result ->
documents = result.value
}

还检查result.values是否为!=null,获取这样的值,同时在结束时检查是否正确映射了集合。

相关内容

最新更新