user1889890
user1889890

Reputation:

App crashes on button touch - onTouch method error?

My app keeps crashing when I click the "startButton". I guess the problem is somewhere within that onTouch method, but I've tried solving the problem for hours; disabling different things inside the startButton.setOnTouchListener doesn't make a difference. Can you find anything wrong?

MediaPlayer mp;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);
    final Button startButton = (Button) this.findViewById(R.id.button1);
    final TextView timeLeft = (TextView) this.findViewById(R.id.timeLeft);
    MediaPlayer.create(getBaseContext(), R.raw.songthingy);


    startButton.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {

                mp.start();
                timeLeft.setText("Status: Initiated");
                startButton.setText("Stop");

                startButton.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        mp.release();

                    }

                });

                new CountDownTimer(30000, 1000) {

                    public void onTick(long millisUntilFinished) {
                        timeLeft.setText("Status: Starting in... "
                                + millisUntilFinished / 1000);
                    }

                    public void onFinish() {
                        timeLeft.setText("Status: Finished");
                    }
                }.start();

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

}

Upvotes: 0

Views: 730

Answers (1)

kosa
kosa

Reputation: 66647

There is no exception stack in question, but one issue I see is:

MediaPlayer mp;

is pointed to null and you are calling

mp.start();

in OnTouchListener, which results in NullPointerException.

I think what you need to do is:

 final TextView timeLeft = (TextView) this.findViewById(R.id.timeLeft);
 mp= MediaPlayer.create(getBaseContext(), R.raw.songthingy);

Upvotes: 1

Related Questions