当我单击“startButton”时,我的应用程序不断崩溃。我猜问题出在onTouch方法中,但是我已经尝试解决了好几个小时。禁用startButton.setOnTouchListener内部的不同内容没有什么区别。你能找到什么错吗?

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;
        }
    });

}

最佳答案

没有问题的异常堆栈,但是我看到的一个问题是:

MediaPlayer mp;

指向null,您正在 call

mp.start();

OnTouchListener中,结果为NullPointerException

我认为您需要做的是:
 final TextView timeLeft = (TextView) this.findViewById(R.id.timeLeft);
 mp= MediaPlayer.create(getBaseContext(), R.raw.songthingy);

09-28 01:46