This happens because the method getSystemService
can return null
.
It is stated as follows (note the annotation @Nullable
):
public abstract @Nullable Object getSystemService(@ServiceName @NonNull String name);
What happens is that the IDE detects the annotation and displays 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 make sure you never cause an NPE, you can make a null check:
if(notifyManager != null) {
notifyManager.notify(id, builder.build());
}
But in practice, it will only be a problem if you pass one name
that does not exist, or try to grab a service from a later Android version than the current device supports.
You can simulate the IDE’s behavior by creating a method with annotation Nullable
:
public @Nullable String getFoo() {
return "1,1";
}
And try to invoke a returned object method:
String foo = getFoo();
foo.split(",");
Notice that now you will see a warning identical to the one you described.
This is a mistake or just a warning?
– Sam
a warning when passing the mouse by cime of 'notify'.
– Robson Cabral
More now in the application is no longer appearing notification, and before was.
– Robson Cabral
No, the notification has really disappeared when I start, as before. What suggestion?
– Robson Cabral
Try:
if(notifyManager != null) { notifyManager.notify(id, builder.build()); }
to remove the warning.– Sam
Thank you. I’ll try here
– Robson Cabral
gave some result?
– Sam
Well, the warning is gone, but it’s not notifying yet. rsrsrsrs
– Robson Cabral
You are using Fragment? Try to replace
getActivity
forgetApplicationContext()
orgetContext()
– Valdeir Psr