[英]“NullPointerException: null cannot be cast to non null type Error” in kotlin
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()
}}}
Here I get error in the line notify = document?.get("notifyTo") as ArrayList<String>
.在这里,我在notify = document?.get("notifyTo") as ArrayList<String>
行中收到错误。
This is my logcat details这是我的 logcat 详细信息
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)`.
Please can anyone help.请任何人都可以帮忙。 Here I am trying to read a array document from firestore.在这里,我试图从 firestore 读取数组文档。
First of all, .addOnSuccessListener
returns the result, not the value so it will obviously cause an exception.首先, .addOnSuccessListener
返回结果,而不是值,因此它显然会导致异常。
var documents: ArrayList<String> = arrayListOf()
c.collection("applicationForm").document(documentid.toString()).get()
.addOnSuccessListener { result ->
documents = result.value
}
also check if result.values is != null , get the value like this, also at the end check if you are mapping the collection correctly.还要检查 result.values 是否为 != null ,获取这样的值,最后还要检查您是否正确映射了集合。
You are correctly gating document?.get(...)
but you are casting the result to an ArrayList.您正确地对document?.get(...)
进行了门控document?.get(...)
但您将结果转换为 ArrayList。
Since either document
is null OR there is no "notifyTo"
key in your document result, you end up basically doing null as ArrayList<String>
.由于"notifyTo"
document
为 null 或文档结果中没有"notifyTo"
键,因此您最终基本上将null as ArrayList<String>
。 Hence the error.因此错误。
To stop getting the crash, you need to do document.get("notifyTo") as? ArrayList<String>
要停止崩溃,您需要将document.get("notifyTo") as? ArrayList<String>
document.get("notifyTo") as? ArrayList<String>
But really want you want to make sure of is that "notifyTo" exists inside your document so that you no longer get a null return value但真的希望您要确保“notifyTo”存在于您的文档中,以便您不再获得空返回值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.