0

I am trying to develop a Notes application where I can save list of notes. These notes will be saved in SQLite DataBase. I have set a button to delete the created note. When I click on this butting during run time (no complete time error) it is giving me a mentioned error. Kindly help in resolving this issue.

I tried to develop this app by reading and copying the code from

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("%")
        })
MBT
  • 21,733
  • 19
  • 84
  • 102
  • @EpicPandaForce could you please reopen the question, because the answers from the linked one about NullPointerException in Java are not much relevant to Kotlin and its KotlinNullPointerException that happens when `!!` operator encounters `null` value. It would also be nice to explain why `context` is null here. – Ilya Mar 24 '19 at 00:59

1 Answers1

0

You're getting a KotlinNullPointerException here because of the failed null assertion in the expression context!! in that line: !! operator ensures that the expression to the left is not null or throws KNPE otherwise.

Here context variable is null by the time it has been accessed in the OnClickListener. By why is it null? I suppose because it was never assigned to something other than null in this code example. In particular, the following part of code looks suspicious:

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

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

Here you assign the value of context to the context variable, but where does that value come from? The closest identifier with this name is the same context variable, which is initially null, so this variable gets null assigned once again.

In fact, IDE even reports Variable 'context' is assigned to itself warning on this line.

Ilya
  • 21,871
  • 8
  • 73
  • 92