android - 如何修复“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("%")
})
解决方案
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
会在这一行报告警告。
推荐阅读
- java - 如何控制 peek 以区别对待最后一个元素?
- vim - 如何使用与默认 .vimrc 不同的 .vimrc
- jira - 消除 Jira 中的原因字段
- mysql - 获取Mysql中id不同的那些行
- angularjs - 缩小后,AngularJS 应用程序未在 Safari 浏览器(<10.1 版本)中加载
- android - IBM MobileFirst 7.1 Cordova Camera 插件在 LG 手机中保存图片
- newrelic - 千分尺添加自定义参数
- xamarin - Xamarin Mobile 与 IdentityServer 3
- lua - LUA iup.text 光标问题
- git - Git:拉动后的第二个(空)FETCH_HEAD文件