DialogFragment getActivity() "might be null" lint warning in AndroidStudio 3.0.1

The answer by @Niklas explains why you get this warning now. I would like to share my thoughts about what you should actually do.

First of all, all this added nullability does is exposing the old design deficiency that was present all these years - this method could always return null (e.g. Fragment detached).

I would prefer if they annotated the return value as @NonNull and throw exception internally if this method is called when the Activity is actually null, but I understand that it would break backward compatibility and as such very risky (though I can hardly see why would anyone call this method when the Activity can actually be null).

So, what should we do about it?

First of all, since the functionality didn't change at all, if the code in question already worked then do what @CommonsWare suggested - either supress the warning or ignore it.

You could also wrap each call into null check with e.g. exception.

What I'm going to do, however, is to put this method in my BaseDialog (which is extended by all other dialogs):

protected FragmentActivity getActivityNonNull() {
    if (super.getActivity() != null) {
        return super.getActivity();
    } else {
        throw new RuntimeException("null returned from getActivity()");
    }
}

Note that all these options effectively state that you don't really expect null to be returned and is OK with app crashing if that happens. That's why I said that I would prefer to have this in support library code instead.

Edit:

A new method was added to support Fragments - requireActivity(). This method is equivalent to getActivityNonNull() descried above (though it throws IllegalStateException if not attached to Activity).

Use this method instead of getActivity() and you should be good.


These methods was added in Revision 27.1.0 Release:Fragments now have requireContext(), requireActivity(), requireHost(), and requireFragmentManager() methods, which return a NonNull object of the equivalent get methods or throw an IllegalStateException.


This is a duplicate of - Android Studio 3.0 lint warnings for references to activity.

tldr; getActivity() got with Support lib 27.0.0 the annotation @Nullable and static analyze tools pick that up now.

Tags:

Java

Android

Lint