Javallion
Javallion

Reputation: 23

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 

Upvotes: 1

Views: 506

Answers (3)

Joffrey
Joffrey

Reputation: 37710

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

Upvotes: 0

Oreste Viron
Oreste Viron

Reputation: 3805

Are you sure you clearly understand how !! operator works ? If this.currentFocus is null, it indicates it should throws a nullpointerexception : https://kotlinlang.org/docs/reference/null-safety.html

Remove the !!, it should work better.

Upvotes: 1

shiftpsh
shiftpsh

Reputation: 1926

!! operator is called the Not-null assertion operator - this will throw NPE if currentFocus is null. Since your view can be null, it's safe to drop the !! operator.

Read:

Upvotes: 2

Related Questions