kotlinandroid-softkeyboardinputmethodmanager

NullPointerException in my Kotlin code despite safeguards


The code snippet below is from my onOptionsItemSelected function. Lines 2-5 below are suppose to hide the soft keyboard if it is showing OR call the activity's finish function otherwise.

I got this piece of code from one of the answers to 'How to Hide a SoftKeyboard' on stack overflow. It works fine on my phone but when I recently submitted my app for internal testing on playstore, I found out that it is throwing NPE sometimes. Can someone explain the logic behind why this might be happening please?

R.id.done -> { 
  val view:View? = this.currentFocus!! // throws null pointer exception
  val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager 
  if (bool && view!=null) { 
    imm.hideSoftInputFromWindow(view.windowToken, 0) 
  } else{ 
    finish() 
  } 
  return true 

Solution

  • The point of the !! operator is to convert a value of nullable type to the non-nullable equivalent while actively ensuring that the value is indeed not null (and throwing an NPE otherwise).

    Here is what your code is actually doing:

    val nonNullView: View = this.currentFocus!! // crashes if null
    val view: View? = nonNullView
    

    As you can see, !! has to throw an exception if the value is null, because a null value cannot be of type View (non nullable).

    In your case, you end up with a nullable type View? anyway, so you don't need the extra temporary restriction imposed by !!, so you may as well just remove it:

    val view: View? = this.currentFocus