-1

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.

Timisorean
  • 1,388
  • 7
  • 20
  • 30
Jack Wilson
  • 6,065
  • 12
  • 29
  • 52
  • Possible duplicate of [Null pointer error with hideSoftInputFromWindow](https://stackoverflow.com/questions/19069448/null-pointer-error-with-hidesoftinputfromwindow) – Ed Holloway-George Aug 28 '18 at 16:09

2 Answers2

4

The java.util.Objects class 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:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    // do your work here
}

(The KITKAT constant is defined to be 19, 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 as Objects.requireNonNull(), you could write this:

InputMethodManager imm =
        (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

if (imm == null) {
    throw new NullPointerException();
}

imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
Ben P.
  • 52,661
  • 6
  • 95
  • 123
0

Try below

    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm != null) {
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
Krishna Sharma
  • 2,828
  • 1
  • 12
  • 23