开发者

Application crash on android

I don't know the reason of the crash.

package com.tct.soundTouch;

//imports ();;;;;;;

    public class Main extends Activity implements OnClickListener{

        private MediaPlayer mp;
        private MotionEvent event;

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            this.requestWindowFeature(Window.FEATURE_NO_TITLE);
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
            setContentView(R.layout.main);

       开发者_C百科     final ImageButton zero = (ImageButton) this.findViewById(R.id.button);
            zero.setOnClickListener(this);

            mp = MediaPlayer.create(this, R.raw.sound);

        }


        public void onClick(View v) {
            switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                mp.setLooping(true);
                mp.start();
                break;

            case MotionEvent.ACTION_UP:
                mp.pause();
                break;

            }
        }

    }

the log

Application crash on android

thanks


I think the problem is in the line switch (event.getAction()) {. Where did you initialize event? I think this causes the NullPointerException.

Btw... You shouldn't name your class main. Use Main at least.


I'm not seeing event being set to a non-null value in the code you posted. Unfortunately, there is no "up" or "down" to a click event received via an OnClickListener.

If you're looking for a toggle-like effect, you might use MediaPlayer#isPlaying():

public void onClick(View v) {
    if (mp.isPlaying()) {
        mp.pause();
    } else {
        mp.setLooping(true);
        mp.start();
    }
}

If you need to handle MotionEvent.UP and MotionEvent.DOWN then you should implement View.OnTouchListener:

@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            mp.setLooping(true);
            mp.start();
            return true;
        case MotionEvent.ACTION_UP:
            mp.pause();
            return true;
    }
    return false;
}

and then set it using setOnTouchListener:

zero.setOnTouchListener(this);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜