【问题标题】:App crashes on button touch - onTouch method error?应用程序在按钮触摸时崩溃 - onTouch 方法错误?
【发布时间】:2013-01-31 22:19:52
【问题描述】:

单击“开始按钮”时,我的应用程序不断崩溃。我猜问题出在 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 = new MediaPlayer();
  • 这些错误非常基本,请在考虑流程的同时进行编码。显然,如果您不初始化对象,它将为空。假设简单的问题,你会为自己节省很多时间。此外,堆栈跟踪是一个死的赠品,它一开始是空的。

标签: java android button crash


【解决方案1】:

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

MediaPlayer mp;

指向null,您正在调用

mp.start();

OnTouchListener 中,结果为NullPointerException

我认为你需要做的是:

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

【讨论】:

  • 同意,OP 应该将mp = 添加到MediaPlayer.create(getBaseContext(), R.raw.songthingy);
猜你喜欢
  • 1970-01-01
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
  • 2021-06-12
  • 2022-01-14
  • 2016-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多