简体   繁体   English

应用程序在按钮触摸时崩溃-onTouch方法错误?

[英]App crashes on button touch - onTouch method error?

My app keeps crashing when I click the "startButton". 当我单击“ startButton”时,我的应用程序不断崩溃。 I guess the problem is somewhere within that onTouch method, but I've tried solving the problem for hours; 我猜问题出在onTouch方法中,但是我已经尝试解决了好几个小时。 disabling different things inside the startButton.setOnTouchListener doesn't make a difference. 禁用startButton.setOnTouchListener内部的其他内容没有什么区别。 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;
        }
    });

}

There is no exception stack in question, but one issue I see is: 没有问题的异常堆栈,但是我看到的一个问题是:

MediaPlayer mp;

is pointed to null and you are calling 指向null并且您正在呼叫

mp.start(); mp.start();

in OnTouchListener , which results in NullPointerException . OnTouchListener ,将导致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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM