【问题标题】:"NullPointerException: null cannot be cast to non null type Error" in kotlinkotlin 中的“NullPointerException:null 不能转换为非 null 类型错误”
【发布时间】:2021-09-30 03:27:35
【问题描述】:

 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&lt;String&gt; 行中出现错误。

这是我的 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)`. 

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

【问题讨论】:

  • 您的document 为空或不包含notifyTo 字段。

标签: android arrays kotlin google-cloud-firestore nullpointerexception


【解决方案1】:

首先,.addOnSuccessListener 返回的是结果,而不是值,所以很明显会导致异常。

    var documents: ArrayList<String> = arrayListOf()

    c.collection("applicationForm").document(documentid.toString()).get()
                .addOnSuccessListener { result ->
                documents = result.value
    }

还要检查 result.values 是否为 != null, 获取这样的值,最后还要检查您是否正确映射集合。

【讨论】:

    【解决方案2】:

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

    由于document 为空或文档结果中没有"notifyTo" 键,您最终基本上会执行null as ArrayList&lt;String&gt;。因此出现错误。

    要停止崩溃,您需要执行document.get("notifyTo") as? ArrayList&lt;String&gt;

    但你真正想要确定的是“notifyTo”存在​​于你的文档中,这样你就不再得到空返回值

    【讨论】:

    • @user16493824 如果有效,请接受答案:)
    猜你喜欢
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    相关资源
    最近更新 更多