首页 > 解决方案 > 如何修复“AndroidRuntime: FATAL EXCEPTION: main, kotlin.KotlinNullPointerException”?尝试删除存储的数据Sqlite db时出错

问题描述

我正在尝试开发一个笔记应用程序,我可以在其中保存笔记列表。这些注释将保存在 SQLite 数据库中。我设置了一个按钮来删除创建的笔记。当我在运行时单击此对接时(没有完整的时间错误),它给了我一个提到的错误。请帮助解决此问题。

我试图通过阅读和复制代码来开发这个应用程序

https://github.com/hussien89aa/KotlinUdemy/tree/master/Android/NoteApp/StartUp

inner class MyNotesAdapter : BaseAdapter {

    var listNotesAdapter = ArrayList<note>()
    var context: Context? = null

    constructor(listNotesAdapter: ArrayList<note>) : super() {
        this.listNotesAdapter = listNotesAdapter
        this.context = context
    }


    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var myView = layoutInflater.inflate(R.layout.ticket, null)
        var myNote = listNotesAdapter[position]
        myView.tvTitle.text = myNote.nodeName
        myView.tvDes.text = myNote.nodeDes


        myView.delete.setOnClickListener(View.OnClickListener {

            var dbManager = DbManager(this.context!!) //This is the line where I am getting error.

            val selectionArgs = arrayOf(myNote.nodeID.toString())
            dbManager.Delete("ID=?", selectionArgs)
            LoadQuery("%")
        })

标签: androidsqlitekotlinnullpointerexception

解决方案


KotlinNullPointerException由于该行中的表达式中的 null 断言失败,您在这里得到一个context!!!!运算符确保左侧的表达式不为 null 或KNPE以其他方式抛出。

这里context的变量在被访问时为空OnClickListener。为什么它为空?我想是因为在此代码示例中它从未被分配给 null 以外的东西。特别是,以下代码部分看起来很可疑:

inner class MyNotesAdapter : BaseAdapter {
    ...
    var context: Context? = null

    constructor(listNotesAdapter: ArrayList<note>) : super() {
        ...
        this.context = context
    }

在这里,您将值context赋给context变量,但该值从何而来?与此名称最接近的标识符是相同的context变量,最初为 null,因此null再次分配此变量。

事实上,IDE 甚至Variable 'context' is assigned to itself会在这一行报告警告。


推荐阅读