Search code examples
android-togglebutton

ToggleButton code in Android Studio unexpectedly crashes the App


My project is a music player that has a ToggleButton for play/pause.

I tried to run a code in Android Studio, but it unexpectedly crashes the App.

I am trying to follow up some tutorials on the internet and YouTube guides, but nothing works so far.

Here is the code that I'm running in the MainActivity:

package com.example.hamzeh.playpausestop;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

    MediaPlayer Sound;
    int pause;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void stop(View view)
    {
        Sound.release();
    }

    public void onToggleClicked(View view)
    {
        boolean checked = ((ToggleButton)view).isChecked();

        if (checked)
        {
            Sound.start();
            //Play
        }
        else
        {
            Sound.pause();
            pause = Sound.getCurrentPosition();
            //Pause
        }

    }

}

Solution

  • Post your logcat result i will give better answer your class have no any initialization of sound object and also check in xml onClick tag is onToggleClicked and stop is defined or not.

    public class MainActivity extends AppCompatActivity {
    
    MediaPlayer Sound;
    int pause;
    //
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // initialize Mediaplayer here for single sound
        Sound= MediaPlayer.create(MainActivity.this, R.raw.UrSoundFileInRawFolder);
    
    }
    
    public void stop(View view){
        Sound.release();
    }
    
    public void onToggleClicked(View view){
        boolean checked = ((ToggleButton)view).isChecked();
    
        if (checked && !Sound.isPlaying() && Sound!=null){
            Sound.start();
        }
        else if(Sound.isPlaying()){
               Sound.pause();
               pause = Sound.getCurrentPosition();
        } esle{
             Toast.makeText(MainActivity.this, "SomeThingWrong", Toast.LENGTH_SHORT).show();
        }
      }
    }