android How to fix: method invocation 'getSystemService'

Viewed 823

I have Fragment that launches a Datepicker. Android Studio is newly throwing an error message: "Method invocation 'getSystemService' may produce 'NullPointerException' on the following code:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    super.onCreateDialog(savedInstanceState);
    // Hide the soft keyboard when the fragment is created.
    InputMethodManager inputManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    ...
}

The suggested "fix" from Android Studio is to "Replace with 'Objects.requireNonNull(getActivity())'"

Doing so then throws another Android Studio error on ".requireNonNull(getActivity())..."

One of the suggested fixes that clears the last error message does this to the code:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
inputManager = (InputMethodManager) Objects.requireNonNull(getActivity()).getSystemService(Context.INPUT_METHOD_SERVICE);
}

But does the above mean that the keyboard will not be hidden for OS < KITKAT? I am looking for a fix for API >=14, not API 19 (KITKAT). What am I missing here?

3 Answers

try

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    super.onCreateDialog(savedInstanceState);
    // Hide the soft keyboard when the fragment is created.
    if (getActivity() != null) {
        InputMethodManager inputManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        ...
    }
}

Method invocation getSystemService may produce NullPointerException is just warning. It tells that you can get NullPointerException because getSystemService(Context.INPUT_METHOD_SERVICE) may return null. You just need do null check :)

It's just a warning. You can pretty safely ignore it.

For better Kotlin compatibility, Google added a bunch of @Nullable and @NotNull annotations to the SDK in API 28. In Java, there's no functional difference, except that you'll now be seeing more of these warnings.

getActivity() usually isn't null in a Fragment, unless you call it during initialization or before the Context is attached.

Related