Method invocation 'notify' may produce 'java.lang.NullPointException'

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());
    
asked by anonymous 24.04.2018 / 02:04

1 answer

1

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.

    
24.04.2018 / 12:56