Toggle button crashes when turned on / off more than once

I can press the toggle button (once) and turn it off (once), but if I touch it a third time, it turns on but never plays in music. From there, when I touch it again to turn it off, it crashes.

public class Main extends Activity {

MediaPlayer mp;
Button startButton;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);
    mp = MediaPlayer.create(getBaseContext(), R.raw.songthing);

    ToggleButton toggle = (ToggleButton) findViewById(R.id.ToggleButton);
    toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            if (isChecked) {
                mp.start();
            } else {
                mp.stop();
            }
        }
    });

    mp.setOnCompletionListener(new OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            mp.release();
        }
    });

}

      

I'm not sure if I should use it in the onCreate method ... I tried to move it, but I'm very confused about all the brackets and it won't work.

A little more on my code ... I'm trying to get the media player to play a song when the toggle button is on and stops when it is off.

EDIT: Logcat says something about java.lang.IllegalStateException

XML:

<ToggleButton
        android:id="@+id/ToggleButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:textOff="Start"
        android:textOn="Stop" />

      

+3


source to share


1 answer


You can read a little about MediaPlayer

states here .
If you call stop()

, you need the prepare()

turntable again before you can start()

.

Once in a Stop state, playback cannot be started until prepare () or prepareAsync () is called to set the MediaPlayer object back to Ready.



If it takes too long to prepare a player, consider using pause()

it and then seekTo(0);

as an alternative.

+2


source







All Articles