0

我正在创建一个小程序,当有人跳跃时播放马里奥跳跃的声音。我可以使用 Z 加速度使程序在达到某个值(如 10 m/s^2)时显示一条消息。我希望它从媒体播放器对象播放声音,但是当我创建媒体播放器对象时,它会使代码崩溃。我将在pastebin上发布代码。

public class MainActivity extends Activity implements SensorEventListener {
        Sensor accelerometer;
        SensorManager sm;
        TextView acceleration;
    MediaPlayer mp = MediaPlayer.create(getBaseContext(),R.raw.jump); //Line 17


        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                sm= (SensorManager)getSystemService(SENSOR_SERVICE);
                accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
                sm.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);           
                acceleration = (TextView) findViewById(R.id.acceleration);             

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.main, menu);
                return true;
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
                // TODO Auto-generated method stub


        }

        @Override
        public void onSensorChanged(SensorEvent event) {
                // TODO Auto-generated method stub     
                acceleration.setText("X: " + event.values[0] + "\nY: " + event.values[1] +  "\nZ: " + event.values[2]);
                if (event.values[2] > 10.8 ) {
                        acceleration.setText("Z IS REALLY BIG!!");
                }
        }

}

添加第 17 行是程序崩溃的原因......

4

1 回答 1

1

你需要分开

MediaPlayer mp = MediaPlayer.create(getBaseContext(),R.raw.jump);

分为以下两部分:

MediaPlayer mp; //keep this where the current line is
mp = MediaPlayer.create(getBaseContext(),R.raw.jump); //Put this in onCreate()

mp您的应用程序崩溃了,因为您在方法主体之外进行了初始化,这意味着它是在onCreate(). 由于您的 Activity 对象onCreate()在被调用之前还没有准备好,因此调用getBaseContext()会导致NullPointerException.

于 2013-05-19T03:03:18.583 回答