SAVVY SAVVY - 4 months ago 8
Android Question

How to play mysic from the list

I am trying to music get the songs from the sd card and displaying the details of the song in the list view and setting itemOnclick Listener in it .I am able to play the song properly ,But when i click a different item in the list view the other song start without stopping the first one here is my code

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Mediafileinfo item = audioList.get(i);
Uri myUri = Uri.parse(item.getData());


mediaPlayer = new MediaPlayer();
if(!mediaPlayer.isPlaying())
{mediaPlayer.reset();
try {
mediaPlayer.setDataSource(MainActivity.this, myUri);
} catch (IOException e) {
e.printStackTrace();
}


try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}

mediaPlayer.start();

}
else if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(MainActivity.this, myUri);
} catch (IOException e) {
e.printStackTrace();
}

try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}

mediaPlayer.start();
}
}
});


I tried to set isPlaying and if the song is playing it will stop it but that also dont work for me any hint or where I am doing wrong ??

Answer

may be caused by this

 mediaPlayer = new MediaPlayer();

when you click,you making a new mediaPlayer ,but the new mediaPlayer isn't playing,so there are two mediaPlayer playing.