Call requires api level 19 current min is 16 java.util.objects#requirenonnull

2.7k Views Asked by At

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.

2

There are 2 best solutions below

0
Ben P. On BEST ANSWER

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);
0
Krishna Sharma On

Try below

    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm != null) {
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }