Search code examples
androidandroid-mediaplayer

Media Player wont stop playing while using Recyclerview


I am having a little bit of an issue with the media player. Currently everything works perfectly except for this one part. I have a recyclerview that I am using to get the URLs and using that to play in the mediaplayer. The only issue is when I click on the position of the recyclerview, it will play the music, but when I click on another position is will overlap the current mediaplayer and won't stop it. I added the code for it to stop and release if the mediaplayer is playing but it wont work. If someone can give me some advice on how to fix this. My code is posted below.

Main Activity

public class MainActivity extends AppCompatActivity {

private RecyclerView mRecyclerView;
private DatabaseReference mDatabase;
private TextView btm_music_text;
private ImageView btm_play;
public static String title,body,url;
private static MediaPlayer mediaPlayer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btm_music_text = (TextView) findViewById(R.id.main_act_text);
    btm_play = (ImageView) findViewById(R.id.main_act_play);
    mRecyclerView = (RecyclerView) findViewById(R.id.mainAct_RV);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    //Database Ref
    mDatabase = FirebaseDatabase.getInstance().getReference().child("/episodes");

    //Set up Firebase Database Adapter
    FirebaseRecyclerAdapter<EpisodeReference, EpisodeViewHolder> recyclerAdapter = new FirebaseRecyclerAdapter<EpisodeReference, EpisodeViewHolder>
            (EpisodeReference.class, R.layout.episode_layout, EpisodeViewHolder.class, mDatabase)

    //Populating View
    {
        @Override
        protected void populateViewHolder(final EpisodeViewHolder viewHolder, final EpisodeReference model, int position) {
            viewHolder.setBody(model.getBody());
            viewHolder.setTitle(model.getTitle());

            viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    title = model.getTitle();
                    body = model.getBody();
                    url = model.getUrl();
                    Uri mUri = Uri.parse(url);

                    btm_music_text.setSelected(true);
                    btm_music_text.setText(title + ": " + body);

                    mediaPlayer = new MediaPlayer();
                    try {
                        mediaPlayer.setDataSource(getApplicationContext(), mUri);
                        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        mediaPlayer.prepare(); //don't use prepareAsync for mp3 playback
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    if (mediaPlayer.isPlaying() && mediaPlayer != null){
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        btm_play.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.selector_play));
                    } else {
                        mediaPlayer.start();
                        btm_play.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.selector_pause));
                    }
                    button_change();
                    /*Intent intent = new Intent(getApplicationContext(), MusicPlayerActivity.class);
                    intent.putExtra("TITLE", model.getTitle());
                    intent.putExtra("BODY", model.getBody());
                    intent.putExtra("URL", model.getUrl());
                    startActivity(intent);*/
                }
            });
        }
    };
    mRecyclerView.setAdapter(recyclerAdapter);
}

private void button_change(){
    btm_play.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (mediaPlayer.isPlaying() && mediaPlayer != null) {
                btm_play.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.selector_play));
                mediaPlayer.pause();
            } else {
                mediaPlayer.start();
                btm_play.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.selector_pause));
            }
        }
    });
}

public static class EpisodeViewHolder extends RecyclerView.ViewHolder {
    View mView;
    TextView tv1;
    TextView tv2;



    public EpisodeViewHolder(View view) {
        super(view);
        mView = view;
        tv1 = (TextView) view.findViewById(R.id.tv1);
        tv2 = (TextView) view.findViewById(R.id.tv2);
    }

    public void setBody(String body) {
        tv2.setText(body);
    }

    public void setTitle(String title) {
        tv1.setText(title);
    }
}
}

Solution

  • You are making a new MediaPlayer before stopping the previous one. Rearrange your code like this

    @Override
        protected void populateViewHolder(final EpisodeViewHolder viewHolder, final EpisodeReference model, int position) {
            viewHolder.setBody(model.getBody());
            viewHolder.setTitle(model.getTitle());
    
            viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
    
                    title = model.getTitle();
                    body = model.getBody();
                    url = model.getUrl();
                    Uri mUri = Uri.parse(url);
    
                    btm_music_text.setSelected(true);
                    btm_music_text.setText(title + ": " + body);
    
                    if (mediaPlayer != null && mediaPlayer.isPlaying()){
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        btm_play.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.selector_play));
                    } else {
                        mediaPlayer = new MediaPlayer();
                        try {
    
                         mediaPlayer.setDataSource(getApplicationContext(), mUri);
    
                 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                            mediaPlayer.prepare(); //don't use prepareAsync for mp3 playback
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        mediaPlayer.start();
                        btm_play.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.selector_pause));
                    }
    
                    button_change();
                    /*Intent intent = new Intent(getApplicationContext(), MusicPlayerActivity.class);
                    intent.putExtra("TITLE", model.getTitle());
                    intent.putExtra("BODY", model.getBody());
                    intent.putExtra("URL", model.getUrl());
                    startActivity(intent);*/
                }
            });
        }