尽管有保障,但我的Kotlin代码中仍然存在NullPointerException

时间:2018-07-30 08:26:28

标签: kotlin android-softkeyboard inputmethodmanager

下面的代码段来自我的onOptionsItemSelected函数。假设下面2-5行隐藏了软键盘(如果显示),否则调用活动的完成功能。

我从堆栈溢出时“如何隐藏软键盘”的答案之一中获得了这段代码。它可以在手机上正常工作,但是当我最近将应用程序提交到Playstore进行内部测试时,我发现它有时会抛出NPE。有人可以解释为什么会发生这种情况的原因吗?

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 

3 个答案:

答案 0 :(得分:2)

!!运算符称为非空断言运算符-如果currentFocus为空,它将抛出NPE。由于您的view可以是null,因此可以放心使用!!运算符。

阅读:

答案 1 :(得分:1)

您确定您清楚了解server.ext('onPreResponse', (request, h) => { const response = request.response; if (!response.isBoom) { return h.continue; } let error = response; if (!error.message && error.output && error.output.payload) { return error.output.payload; } error = new Error(error.message); return Boom.boomify(error, {statusCode: 400}); }); 运算符的工作原理吗?如果!!为null,则表明它应该抛出nullpointerexception: https://kotlinlang.org/docs/reference/null-safety.html

删除this.currentFocus,它应该会更好。

答案 2 :(得分:0)

!!运算符的作用是将可空类型的值转换为不可为空的等效值,同时积极确保该值确实不为空(否则抛出NPE)。

这是您的代码实际在做什么:

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

如您所见,如果该值为null,则!!必须引发异常,因为null值不能为View类型(不可为null)。

在您的情况下,无论如何,您最终都会使用可为空的类型View?,因此您不需要!!施加的额外临时限制,因此也可以将其删除:

val view: View? = this.currentFocus