为什么创建媒体播放器对象会使我的android代码崩溃?
我正在制作一个小程序,当有人跳跃时播放马里奥跳跃音。 我可以使用Z加速度使程序在达到特定值(如10 m/s^2)时显示消息。我想让它播放来自媒体播放器对象的声音,但当我创建媒体播放器对象时,它会使代码崩溃。我会在pastebin上发布代码为什么创建媒体播放器对象会使我的android代码崩溃?,android,android-mediaplayer,accelerometer,Android,Android Mediaplayer,Accelerometer,我正在制作一个小程序,当有人跳跃时播放马里奥跳跃音。 我可以使用Z加速度使程序在达到特定值(如10 m/s^2)时显示消息。我想让它播放来自媒体播放器对象的声音,但当我创建媒体播放器对象时,它会使代码崩溃。我会在pastebin上发布代码 public class MainActivity extends Activity implements SensorEventListener { Sensor accelerometer; SensorManager sm
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行的添加导致程序崩溃 您需要拆分
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()之前执行的。由于您的活动对象在调用onCreate()
之前尚未准备好,因此调用getBaseContext()
会导致NullPointerException
谢谢!真是太棒了。