Search code examples
javaandroidandroid-sensors

Android - sensor or listener is null


I am trying to implement a sensor listener in my app, and it throws a sensor or listener is null error at the mSensorManager.registerListener(sensorEventListener, mSensor, mSensorManager.SENSOR_DELAY_FASTEST); line. Here is my full code:

    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));*/
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR);
    sensorEventListener = new SensorEventListener() {
        public void onSensorChanged(SensorEvent event) {
            double xAxis = event.values[0];
            TextView textView = (TextView) findViewById(R.id.rotation);
            textView.setText(String.valueOf(xAxis));
        }

        public void onAccuracyChanged(Sensor s, int i) {

        }
    };

    mSensorManager.registerListener(sensorEventListener, mSensor, mSensorManager.SENSOR_DELAY_FASTEST);

I checked and the sensor was actually null. What am I doing wrong? Thanks.

EDIT : The device is a 2nd Gen. Moto G.


Solution

  • The reason is the fact that Sensor.TYPE_GAME_ROTATION_VECTOR is not supported on the device. Therefore the sensor was null.