At first the code is:
private void hideKeyboard()
{
View view = getCurrentFocus();
if (view != null)
{
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
the warning message is :
Method invocation 'hideSoftInputFromWindow' may produce 'java.lang.NullPointerException'
so I changed code under the hint to:
private void hideKeyboard()
{
View view = getCurrentFocus();
if (view != null)
{
((InputMethodManager) Objects.requireNonNull(getSystemService(Context.INPUT_METHOD_SERVICE)))
.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
this time the warning message is:
call requires api level 19 current min is 16 java.util.objects#requirenonnull
How can I figure out? Thank you.
The
java.util.Objectsclass was added to the Android platform in API 19, so trying to use that class and its methods on any device running API 18 or lower will cause a crash.In general, you can work around this by checking the API level of the device at runtime, using code like this:
(The
KITKATconstant is defined to be19, so, in this example, our code would only run on devices that have API 19 or newer.)However, in your particular case, you really just want to get rid of the compiler warning; you don't have to use
Objects.requireNonNull()to do so. If you want the same behavior asObjects.requireNonNull(), you could write this: