Search code examples
androidandroid-mediaplayer

Android: OnItemClickListener not working the way I expected


I wrote a code that responds to the list view's item click. I intended that the clicked item on the list would return the URI of the media source through the Toast message, and start playing.

Here is the code.

lvAlarmTones.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        ringtone = ringtoneSources.get(position);
        Uri toneUri = Uri.parse(ringtone);
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(ChooseAlarmToneActivity.this, toneUri);
            mediaPlayer.start();
            Log.i(ApplicationManager.LOG, "Media loaded: " + ringtone);

        } catch (IOException e) {
            Toast.makeText(ChooseAlarmToneActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        Toast.makeText(ChooseAlarmToneActivity.this, ringtone, Toast.LENGTH_SHORT).show();
    }
});

When I run this code, I manage to successfully get the Toast with the URI, but I still fail to have the media played.


Solution

  • I solved the problem by modifying the code as follows.

        lvAlarmTones.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                ringtone = ringtoneSources.get(position);
                Uri toneUri = Uri.parse(ringtone);
    
                if(mediaPlayer != null) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                }
                mediaPlayer = MediaPlayer.create(ChooseAlarmToneActivity.this, toneUri);
                mediaPlayer.start();
                Toast.makeText(ChooseAlarmToneActivity.this, ringtone, Toast.LENGTH_SHORT).show();
            }
        });