Why am I getting null.p.ex. on startForegrund?

I want to make a notification to control my music player, and therefore I want to get the foreground working.

My code is:

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
protected void onStop(){
    super.onStop();
    System.out.println("Stop");
    Toast.makeText(this,"Stopped",Toast.LENGTH_SHORT).show();
    if(play_media.isPlaying()){
        PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
                new Intent(getApplicationContext(), MainActivity.class),
                PendingIntent.FLAG_UPDATE_CURRENT);
        Notification notification = new Notification.Builder(mContext)
                .setContentTitle("Playing")
                .setContentText("playing a song")
                .setSmallIcon(R.drawable.ic_play)
                .setLargeIcon(list.get(mDrawerList.getCheckedItemPosition()).getAlbum_Art())
                .setContentIntent(pi)
                .build();

        mediaPlayerService =  new MediaPlayerService();
 322:       mediaPlayerService.startForeground(NOTIFICATION_ID,notification);
    }
}

Exception thrown by startForeground:

02-12 18:06:08.935    4405-4405/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.Driiinx.musicslide, PID: 4405
java.lang.RuntimeException: Unable to stop activity {...com.Driiinx.musicslide.MainActivity}: java.lang.NullPointerException: class name is null
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3188)

...

Caused by: java.lang.NullPointerException: class name is null
        at android.content.ComponentName.<init>(ComponentName.java:63)
        at android.app.Service.startForeground(Service.java:643)
        at com.Driiinx.musicslide.MainActivity.onStop(MainActivity.java:322)

Thank!

+3
source share
1 answer

The solution is simple:

  • start the service explicitly (e.g. in Activity)

    Intent serviceIntent = new Intent(this, TheService.class);  
    startService(serviceIntent);
    
  • in the service onCreate()you should callstartForeground(...)

    Notification notification = ...;
    startForeground(101, notification);
    

The wrong code that caused your problem is creating the service:

    mediaPlayerService =  new MediaPlayerService();
+2
source

All Articles