Search code examples
androidkotlinillegalargumentexception

java.lang.IllegalArgumentException : Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull


I'm getting this error

java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter event

for the line

override fun onEditorAction(v: TextView, actionId: Int, event: KeyEvent)

Following is the entire code. This code was originally in java, I converted it to Kotlin using Android Studio, but now I'm getting this error. I tried rebuilding and cleaning the project, but that didn't work.

val action = supportActionBar //get the actionbar
action!!.setDisplayShowCustomEnabled(true) //enable it to display a custom view in the action bar.
action.setCustomView(R.layout.search_bar)//add the custom view
action.setDisplayShowTitleEnabled(false) //hide the title

edtSearch = action.customView.findViewById(R.id.edtSearch) as EditText //the text editor


//this is a listener to do a search when the user clicks on search button
edtSearch?.setOnEditorActionListener(object : TextView.OnEditorActionListener {
    override fun onEditorAction(v: TextView, actionId: Int, event: KeyEvent): Boolean {
    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
         Log.e("TAG","search button pressed")  //doSearch()
         return true
        }
     return false
    }
})

Solution

  • The last parameter can be null, as described by the docs:

    KeyEvent: If triggered by an enter key, this is the event; otherwise, this is null.

    So what you have to do is make the Kotlin type nullable to account for this, otherwise the injected null check will crash your application when it gets a call with a null value as you've already seen it:

    edtSearch?.setOnEditorActionListener(object : TextView.OnEditorActionListener {
        override fun onEditorAction(v: TextView, actionId: Int, event: KeyEvent?): Boolean {
            ...
        }
    })
    

    More explanation about platform types in this answer.