我有一个显示歌曲列表的RecyclerView,我已经用它成功地实现了点击监听器,并用日志验证了它。现在我想在点击事件时播放这首歌。当我第一次点击某个项目时,歌曲开始播放,但如果我再点击任何其他项目,应用程序就会崩溃
这是我的RecycleServiceClickListener
SongAdapter songAdapter = new SongAdapter(getContext(), songsList, new RecyclerViewClickListener() {
@Override
public void onClick(View view, int position) {
Toast.makeText(getContext(), "You clicked on Ssong "+songsList.get(position).getSongName(), Toast.LENGTH_SHORT)
.show();
songPath = songsList.get(position).getUrl();
Log.v("Song Path", songPath);
if(mp.isPlaying())
releaseMediaResources();
playSong();
}
});
recyclerView.setAdapter(songAdapter);
这是我的播放歌曲的方法
private void playSong () {
if(!songPath.equals("")) {
try {
mp.setDataSource(songPath);
} catch (Exception e) {
Log.e("Home Fragment", "Error setting song Url", e);
}
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.reset();
mp.release();
}
});
}
}
这是我的releaseMediaResources
private void releaseMediaResources() {
mp.stop();
mp.reset();
mp.release();
}
这些是错误
java.lang.IllegalStateException
at android.media.MediaPlayer.isPlaying(Native Method)
at com.ashutosh.prototype4.HomeFragment.playSong(HomeFragment.java:159)
at com.ashutosh.prototype4.HomeFragment.releaseMediaResources(HomeFragment.java:192)
at com.ashutosh.prototype4.HomeFragment.access$100(HomeFragment.java:31)
at com.ashutosh.prototype4.HomeFragment$2.onClick(HomeFragment.java:94)
at com.ashutosh.prototype4.SongAdapter$1.onClick(SongAdapter.java:50)
据我所知,主要问题在于设置媒体播放器,因为当我只显示toast消息时,根本没有问题,但一旦我将媒体播放器实现为点击方式,就会发生崩溃