MediaPlayer error: Attempt to invoke virtual method ‘void android.media.MediaPlayer.start()’ on a null object reference

I'm trying to make an app to play music files from the internal storage of the phone.

This is the first method where all the songs are listed in a ListView.

    public void fileSearch() {
    String[] loadSongs = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME};
    Cursor audioCursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, loadSongs, null, null, null);
    if (audioCursor != null) {
        if (audioCursor.moveToFirst()) {
            do {
                int audioIndex = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);

                audioList.add(audioCursor.getString(audioIndex));
            } while (audioCursor.moveToNext());
        }
    }
    audioCursor.close();
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, audioList);
    listSongs.setAdapter(adapter);
    listSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectedSong(position);
        }
    });



}

And this method should be playing the song selected by the user in the previous list.

 public void selectedSong(int position) {
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, audioList);
    Toast.makeText(MainActivity.this, "You  have selected the song:" + adapter.getItem(position), Toast.LENGTH_SHORT).show();
    File songSelectedPath = getFileStreamPath(adapter.getItem(position));

    Uri uri = Uri.fromFile(songSelectedPath);
    Log.d("Adapter", "AdapterToStringPath: " + uri);
    Log.d("Pointer", "Pointer: " + position);

    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer = MediaPlayer.create(this,uri);
    mediaPlayer.start();
}

The error comes from this line mediaPlayer = MediaPlayer.create(this,uri);

Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference


Read more here: https://stackoverflow.com/questions/67170000/mediaplayer-error-attempt-to-invoke-virtual-method-void-android-media-mediapla

Content Attribution

This content was originally published by T.RY at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: