Method Invocation 'notify' may Produce 'java.lang.Nullpointexception'

Asked

Viewed 194 times

0

NotificationCompat.Builder builder = new NotificationCompat.Builder(getActivity(),"M_CH_ID");
    builder.setAutoCancel( true )
            .setSmallIcon( R.drawable.icon_notificacao )
            .setContentTitle( "RPfm 105.3" )
            .setContentText( "Ao Vivo" );
    int id = 1;
    NotificationManager notifyManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
    notifyManager.notify(id, builder.build());
  • This is a mistake or just a warning?

  • a warning when passing the mouse by cime of 'notify'.

  • More now in the application is no longer appearing notification, and before was.

  • No, the notification has really disappeared when I start, as before. What suggestion?

  • Try: if(notifyManager != null) { notifyManager.notify(id, builder.build()); } to remove the warning.

  • Thank you. I’ll try here

  • gave some result?

  • Well, the warning is gone, but it’s not notifying yet. rsrsrsrs

  • You are using Fragment? Try to replace getActivity for getApplicationContext() or getContext()

Show 4 more comments

1 answer

1


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.