Jan Fous
Jan Fous

Reputation: 33

NullPointerException on getSystemServiceName(...) call

This piece of code throws java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getSystemServiceName(java.lang.Class)' on a null object reference

MainActivity.java

public class MainActivity extends AppCompatActivity {

...

    protected void main() {
        ArrayList<Channel> channelArrayList = channels();


        for (int i = 0; i < channelArrayList.size(); i++) {
            try {
                Log.i("Channel", "Attempting to create channel: '" + channelArrayList.get(i).getChannel_id() + "'");
                this.createChannel(channelArrayList.get(i));

            } catch (Exception exception) {
                Log.e("Channel", "Attempt to create channel '" +  channelArrayList.get(i).getChannel_id() + "' failed - Exception " + exception);

            }
        }
    }

...

    public void createChannel(Channel channel) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            NotificationChannel notificationChannel = new NotificationChannel(
                                                          channel.getChannel_id(),
                                                          channel.getChannel_name(), 
                                                          channel.getChannel_importance()
                                                      );
            notificationChannel.setDescription(channel.getChannel_description());

            NotificationManager notificationManager;
            notificationManager = getSystemService(NotificationManager.class); //error occurs here

            notificationManager.createNotificationChannel(notificationChannel);
        }

    }
}

Note that main activity is not actually what you would expect the main activity to be. It's just a class that's called in the actual main activity (called LauncherActivity.java) like this:

LauncherActivity.java

   protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ...

        MainActivity mainActivity = new MainActivity();
        mainActivity.main();
  }

Full exception message

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.company.app, PID: 16793
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.company.app/com.company.app.LauncherActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getSystemServiceName(java.lang.Class)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getSystemServiceName(java.lang.Class)' on a null object reference
        at android.content.ContextWrapper.getSystemServiceName(ContextWrapper.java:713)
        at android.content.Context.getSystemService(Context.java:3156)
        at com.company.app.MainActivity.createChannel(MainActivity.java:91)
        at com.company.app.MainActivity.main(MainActivity.java:74)
        at com.company.app.LauncherActivity.onCreate(LauncherActivity.java:61)
        at android.app.Activity.performCreate(Activity.java:6975)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
        at android.os.Handler.dispatchMessage(Handler.java:105) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6541) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

Any idea what's causing this issue and how to fix it?

Upvotes: 0

Views: 201

Answers (1)

tynn
tynn

Reputation: 39843

You should never instantiate an activity directly!

MainActivity mainActivity = new MainActivity();

Like this the base context is not attached and therefore null.

If you want to reuse the main() method, make it static and provide a Context as parameter.

protected static void main(Context context) {
    ArrayList<Channel> channelArrayList = channels();

    for (int i = 0; i < channelArrayList.size(); i++) {
        try {
            Log.i("Channel", "Attempting to create channel: '" + channelArrayList.get(i).getChannel_id() + "'");
            createChannel(context, channelArrayList.get(i));
        } catch (Exception exception) {
            Log.e("Channel", "Attempt to create channel '" +  channelArrayList.get(i).getChannel_id() + "' failed - Exception " + exception);
        }
    }
}

private static void createChannel(Context context, Channel channel) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(
                  channel.getChannel_id(),
                  channel.getChannel_name(), 
                  channel.getChannel_importance());
        notificationChannel.setDescription(channel.getChannel_description());

        NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(notificationChannel);
    }
}

Upvotes: 1

Related Questions