Search code examples
androidaudionullpointerexceptionandroid-mediaplayerintentfilter

Null Pointer Exception when calling mediaPlayer.start() : Android


Basically what I want is to allow the user to select a audio file from their device and once they do, this activity starts and the music/audio file will be played. For that I've used included an intent-filter in my Android Manifest File, and its working fine, there are no errors.

The problem is when I call mediaPlayer.start() I get a Null Pointer Exception. From what I've read so far, this happens because MediaPlayer fails to create a object or something... the MediaPlayer.cretae() returns null.

The following is the whole code for this Activity:

public class IntentPlayerActivity extends AppCompatActivity {

    TextView song_name,artist_name;
    ImageView playPauseBtn;
    SeekBar seekBar;

    static Uri uri;
    static MediaPlayer mediaPlayer = new MediaPlayer();

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

        initViews();
        Intent intent = getIntent();
        if (intent.getAction().equals(Intent.ACTION_VIEW)){

            Log.d("Intent Player_Activity:", " File Path: "+ intent.getData().getPath());

            playPauseBtn.setImageResource(R.drawable.ic_pause_circle_outline);
            uri = Uri.parse(intent.getData().getPath());
            Log.d("Intent Player_Activity:", " URI: "+uri.toString());

            if (mediaPlayer != null){
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
                mediaPlayer.start();
            }else {
                mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
                mediaPlayer.start();
            }
        }
    }

    private void initViews() {
        song_name = findViewById(R.id.song_name);
        artist_name = findViewById(R.id.song_artist);
        playPauseBtn = findViewById(R.id.play_pause);
        seekBar = findViewById(R.id.seekBar);
    }
}   

I'm hopping someone could explain what MediaPlayer.create() dose and what could be causing it to fail, for my case I don't believe the audio file is an invalid format or the specified media file cannot be found. I think its something else.


Solution

  • Delete:

    uri = Uri.parse(intent.getData().getPath());
    

    Instead, pass intent.getData() to MediaPlayer.create():

    mediaPlayer = MediaPlayer.create(getApplicationContext(),intent.getData());