2

I've two radio buttons in a radiogroup and on selection of one radio button it will start music and stop the other sound and on selection of other it will start the next song and stop the previous song. The problem is I'm unable to stop the music. The song keeps on playing in the background. I'm using dialog box to show radio buttons and getting the input from user on button'c click. The length of each song is greater than 3 minutes. I've searched the internet and tried multiples solution but no solution is working. Below is the code I've used:

btnDone.setOnClickListener(view.onClickListener)
{
  @Override
  public void onClick(View view)
  {
   boolean checked = radioButton1.isChecked();
   boolean checked1 = radioButton2.isChecked();
   MediaPlayer mediaPlayer = MediaPlayer.create(this,R.raw.song1);
   MediaPlayer mediaPlayer2 = MediaPlayer.create(this,R.raw.song2);

   if(checked && !checked1)
   {
    mediaPlayer.start();  

   }else if(checked1 && !checked)
   {
    try{
       if(mediaPlayer !=null)
       { 
        if(mediaPlayer.isPlaying())
         {mediaPlayer.stop;
          mediaPlayer.release;
         mediaPlayer = null; 
         }
         }
       }
       catch(Exception e)
       {e.printStackTrace(); }
      }



           }
         }

1 Answers1

0

IMO your else if(checked1 && !checked1) condition not working properly so try else if(checked1 && !checked) try below code

    btnDone.setOnClickListener(view.onClickListener)
{
  @Override
  public void onClick(View view)
  {
   boolean checked = radioButton1.isChecked();
   boolean checked1 = radioButton2.isChecked();
   MediaPlayer mediaPlayer = MediaPlayer.create(this,R.raw.song1);
   MediaPlayer mediaPlayer2 = MediaPlayer.create(this,R.raw.song2);

   if(checked && !checked1)
   {
    mediaPlayer.start();  

   }else if(checked1 && !checked) //change here
   {
    try{
       if(mediaPlayer !=null)
       { 
        if(mediaPlayer.isPlaying())
         {mediaPlayer.stop(); // also change here
          mediaPlayer.release();  //change here
         mediaPlayer = null; 
         }
         }
       }
       catch(Exception e)
       {e.printStackTrace(); }
      }



           }
         }
Omkar
  • 3,040
  • 1
  • 22
  • 42
  • There was typo mistake. I've updated the code. Can you look at it again? –  Dec 23 '17 at 06:08
  • also correct Typo mistake mediaPlayer.stop(); mediaPlayer.release(); here brackets **()** – Omkar Dec 23 '17 at 06:13