-1

I was developing a Music App but whenever I am closing the App, it shows "Unfortunately, Music App has stopped" error. I checked the logcat and this is the cause of the error:

 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference

I don't understand why this error is showing because I am closing the app and this line(where the error showed i guess) was not supposed to get executed.

Below are my java files.

MainActivity.java:

public class MainActivity extends AppCompatActivity {
ListView lv;
Button start,next,prev;
MyAdapter myAdapter;
String icon;
int SongPosition;
 ArrayList<String> songList= new ArrayList<String>();
ArrayList<String> songPath= new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     GetFiles(getContentResolver());
    lv =(ListView)findViewById(R.id.list);
    myAdapter = new MyAdapter();
   lv.setAdapter(myAdapter);

    icon = "resume";

    start = (Button)findViewById(R.id.button);
    next = (Button)findViewById(R.id.next);
    prev = (Button)findViewById(R.id.prev);

    //Pause/Resume playing
    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //startService(new Intent(getBaseContext(),MyService.class));
           // mynotification();
            switch (icon) {
                case "resume":
                    Intent iPause = new Intent(MainActivity.this, MyService.class);
                    iPause.putExtra("STATUS", 2);
                    startService(iPause);
                    icon = "pause";
                    start.setBackgroundResource(android.R.drawable.ic_media_play);

                    break;
                case "pause":
                    Intent iResume = new Intent(MainActivity.this,MyService.class);
                    iResume.putExtra("STATUS",3);
                    startService(iResume);
                    icon = "resume";
                    start.setBackgroundResource(android.R.drawable.ic_media_pause);
                    break;
                default:
                    Toast.makeText(MainActivity.this, "invalid", Toast.LENGTH_SHORT).show();
            }
        }
    });

    //next track
    next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             SongPosition =SongPosition+1;
            String nextSongName = songList.get(SongPosition);
            String nextSongPath = songPath.get(SongPosition);

            Intent nextIntent = new Intent(MainActivity.this,MyService.class);
            nextIntent.putExtra("SONG_NAME",nextSongName);
            nextIntent.putExtra("SONG_PATH",nextSongPath);
            nextIntent.putExtra("STATUS",1);
            startService(nextIntent);
        }
    });

    //previous track
    prev.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //stopService(new Intent(getBaseContext(),MyService.class));
            // mynotification();
             SongPosition = SongPosition-1;
            String prevSongName = songList.get(SongPosition);
            String prevSongPath = songPath.get(SongPosition);

            Intent nextIntent = new Intent(MainActivity.this,MyService.class);
            nextIntent.putExtra("SONG_NAME",prevSongName);
            nextIntent.putExtra("SONG_PATH",prevSongPath);
            nextIntent.putExtra("STATUS",1);
            startService(nextIntent);
        }
    });

    //display all songs
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

            String songName = songList.get(position);
            SongPosition = position;
            String Path = songPath.get(position);

            int state = 1;
            Intent lvintent = new Intent(MainActivity.this,MyService.class);
            lvintent.putExtra("SONG_NAME",songName);
            lvintent.putExtra("SONG_PATH",Path);
            lvintent.putExtra("STATUS",state);
            startService(lvintent);
            start.setBackgroundResource(android.R.drawable.ic_media_pause);
        }
    });
}

public void GetFiles(ContentResolver contentResolver)
{
    Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Cursor musicCursor = contentResolver.query(musicUri, null, null, null, null);

    if(musicCursor!=null && musicCursor.moveToFirst()) {
        //get columns
        int titleColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
        int pathColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.DATA);
        //Toast.makeText(this, songPath, Toast.LENGTH_SHORT).show();
        while (musicCursor.moveToNext()) {
            String title = musicCursor.getString(titleColumn);
            String path = musicCursor.getString(pathColumn);

            songPath.add(path);
            songList.add(title);
        }
    }
    musicCursor.close();
}

public class MyAdapter extends BaseAdapter
{
    LayoutInflater mInflater;
    public MyAdapter()
    {
        mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        return songList.size();
    }
    @Override
    public Object getItem(int position) {
        return position;
    }
    @Override
    public long getItemId(int position) {
        return 0;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (convertView==null)
        {
            v = mInflater.inflate(R.layout.musiclist,null);
        }
        TextView musicName = (TextView)v.findViewById(R.id.musicName);
        musicName.setText(songList.get(position));
        return v;
    }
}

 @Override
protected void onStart() {

    Intent intent = new Intent(MainActivity.this,MyService.class);
    startService(intent);
    start.setBackgroundResource(android.R.drawable.ic_media_play);
    super.onStart();
}}

MyService.java

public class MyService extends Service {
String SongName,SongPath;
int getStatus;
private MediaPlayer player;
private int Songpos;
SharedPreferences settings;
SharedPreferences.Editor editor;
public static final String MyPREFERENCES = "MyPrefs" ;


@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

public void onCreate() {
    super.onCreate();
    Songpos=0;
    player = new MediaPlayer();
   // settings = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
   // editor = settings.edit();
    //String storedName = settings.getString("name","");
  //  String storedPath = settings.getString("path","");
}

@Override
public int onStartCommand(Intent intent,int flags, int startId) {
    SongName = intent.getStringExtra("SONG_NAME");
    SongPath = intent.getStringExtra("SONG_PATH");
     getStatus=intent.getIntExtra("STATUS",0);
    if (getStatus==1) {
        player.reset();
        try {
            player.setDataSource(SongPath);
            player.prepare();
            player.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    else if (getStatus==2)
    {
        onPause();

    }
    else if (getStatus==3)
    {
        onResume();
    }
    return super.onStartCommand(intent, flags, startId);
}

public void onPause(){
    player.pause();
    Songpos= player.getCurrentPosition();
}

public void onResume() {
    player.seekTo(Songpos);
    player.start();
}

@Override
public void onDestroy() {
    player.reset();
    player.release();
    super.onDestroy();
}}
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Zoe May 14 '17 at 15:24

3 Answers3

1

Since at the end of your onStartCommand() implementation you are calling super.onStartCommand(), which by default returns START_STICKY or START_STICKY_COMPATIBILITY, your service can be restated with a null intent. As a result you do need to check that the intent is not null, and then handle that case as needed by your app.

See the following links for details: https://developer.android.com/reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int) https://developer.android.com/reference/android/app/Service.html#START_STICKY

onStartCommand

added in API level 5 int onStartCommand (Intent intent, int flags, int startId) Called by the system every time a client explicitly starts the service by calling startService(Intent), providing the arguments it supplied and a unique integer token representing the start request. Do not call this method directly.

For backwards compatibility, the default implementation calls onStart(Intent, int) and returns either START_STICKY or START_STICKY_COMPATIBILITY.

If you need your application to run on platform versions prior to API level 5, you can use the following model to handle the older onStart(Intent, int) callback in that case. The handleCommand method is implemented by you as appropriate:

START_STICKY

added in API level 5 int START_STICKY Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.

Constant Value: 1 (0x00000001)

nPn
  • 16,254
  • 9
  • 35
  • 58
0

Please post whole of logcat error.
BTW I guess your intent in onStartCommand() method have not required extra data.
For example in start OnClickListener you passed only STAUS extra, but SONG_NAME and SONG_PATH have not passed to intent extra.
If you have not any related data for that intent, must handle it in onStartCommand() method.

Naruto Uzumaki
  • 2,019
  • 18
  • 37
-1
SongName = intent.getStringExtra("SONG_NAME");
SongPath = intent.getStringExtra("SONG_PATH");

One of those two line causes the error, as the message says "Nullpointer .getStringExtra" So what happens here? Obv. your service tries to restart (STICKY?) when the app closes.

It is very easy to avoid, just put a default in the getStringExtra call and react on that or simply call hasExtra

if (intent.hasExtra("SONG_NAME")) {
   // do your stuff
} else {
  Log.e("INTENT", "No intent extra. Exiting.");
  return;
}

Something like that, just to get you started. Hope this helps, Cheers

Grisgram
  • 3,105
  • 3
  • 25
  • 42