I can touch the toggle button on (once) and off (once), but if I touch it a third time, it turns on but never plays the 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 have it within the onCreate method… I’ve tried to move it but I get very confused with all the brackets and it doesn’t work out.
A little more about my code… I’m trying to get the media player to play a song when the toggle button is on and stop it when its 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" />
You can read a bit about the
MediaPlayerstates here.If you call
stop(), you have toprepare()the player again before you canstart()it.If preparing the player takes too long, consider using
pause()followed byseekTo(0);as an alternative.