网上看了个重力感应的编程,但是出现the appilication has stopped unexpectedly,please try again
debug 发现有异常 java.lang.NullPointerException
大家帮忙看看是什么问题??
代码如下:package com.ray.test;   import android.app.Activity;   import android.os.Bundle;   import android.hardware.SensorManager;   import android.hardware.Sensor;   import android.hardware.SensorEventListener;   import android.hardware.SensorEvent;       public class SensorTest extends Activity {       private SensorManager sensorMgr;       Sensor sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);       private float x, y, z;       protected void onCreate(Bundle savedInstanceState) {           super.onCreate(savedInstanceState);           sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);           SensorEventListener lsn = new SensorEventListener() {               public void onSensorChanged(SensorEvent e) {                   x = e.values[SensorManager.DATA_X];                      y = e.values[SensorManager.DATA_Y];                      z = e.values[SensorManager.DATA_Z];                   setTitle("x="+(int)x+","+"y="+(int)y+","+"z="+(int)z);               }                              public void onAccuracyChanged(Sensor s, int accuracy) {               }           };           //注册listener,第三个参数是检测的精确度           sensorMgr.registerListener(lsn, sensor, SensorManager.SENSOR_DELAY_GAME);       }          }  

解决方案 »

  1.   

    Sensor sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);   这句出错了,sensorMgr还没有初始化就调用了。  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);   Sensor sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);   //放在初始化以后。

    这样改就好了。
      

  2.   

    http://dev.10086.cn/cmdn/wiki/index.php?edition-view-6471-1.html,可用按这个你研究一番
      

  3.   

    yyy025025025大哥说的没错,我试过了就是这样的,运行的很好!学习了!