0

I want to register a SENSOR_ACCELEROMETER in a service, but it turns out to be a nullexception.Following is my code:

 asensor = new AccerSensor(context);//the sensoreventlistener
 Log.i("wogua", "creating"+asensor.toString());
 manager.registerListener(asensor,manager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);


 Exception:

Caused by: java.lang.NullPointerException::

    at com.wogua.mobileprotected.service.LostProtectService.onCreate(LostProtectService.java:36)

I dont know what the problem is , the instance of the sensoreventlistener is not null::::com.wogua.mobileprotected.sensor.AccerSensor@41bf3f20

how could this to be null,:::manager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);

honeypig
  • 39
  • 4

2 Answers2

1

This is the way that works for me :

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

    if (mAccelerometer != null) {
        // Success! There's an accelerometer
        mSensorManager.registerListener(this, mAccelerometer,
                SensorManager.SENSOR_DELAY_FASTEST);
    } else {
        Toast.makeText(this, "This device doesnt support accelerometer",
                Toast.LENGTH_SHORT).show();
        stopSelf();
    }
slezadav
  • 5,936
  • 6
  • 33
  • 61
  • ok , let me check ,whether mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); is null or not – honeypig Nov 23 '12 at 09:41
0

manager is not initialized, more than sure about it

Alex Filipovici
  • 29,732
  • 5
  • 50
  • 76