This happens because the getSystemService
method can return null
.
It is declared as follows (note the @Nullable
annotation):
public abstract @Nullable Object getSystemService(@ServiceName @NonNull String name);
What happens is that the IDE detects the annotation and shows a warning.
NotificationManager notifyManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
// Neste momento, a IDE "entende" que notifyManager pode ser nulo,
// e a seguinte chamada de método poderia lançar um NullPointerException:
notifyManager.notify(id, builder.build());
To ensure that you never cause an NPE, you can do a null check :
if(notifyManager != null) {
notifyManager.notify(id, builder.build());
}
But in practice, this will only be a problem if you pass a name
that does not exist, or try to grab a service from an Android version later than the current device supports.
You can simulate the behavior of the IDE by creating a method with the annotation Nullable
:
public @Nullable String getFoo() {
return "1,1";
}
And try to invoke a method of the returned object:
String foo = getFoo();
foo.split(",");
Please note that you will now see a warning similar to what you described.