1

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 
Javallion
  • 23
  • 5

3 Answers3

2

!! 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:

shiftpsh
  • 1,926
  • 17
  • 24
1

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.

Joffrey
  • 32,348
  • 6
  • 68
  • 100
Oreste Viron
  • 3,592
  • 3
  • 22
  • 34
0

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
Joffrey
  • 32,348
  • 6
  • 68
  • 100
  • The safe dereference operator itself should never throw an NPE, but maybe it's something else around it that's causing the NPE, but we would need to see the code to be sure. Please ask another question for this – Joffrey Sep 30 '20 at 14:25