我正在创建一个小程序,当有人跳跃时播放mario跳音。 我可以使用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行的添加使程序崩溃......
答案 0 :(得分: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
。