Search code examples
androidnullpointerexceptionaccelerometerandroid-sensorsdisplayobject

javaNullPointer on display.getRotation()


After having comment all my code to know from where the error was, i found that it came from mDisplay.getRotation(). The general idea of my code is to get the good information from the accelerometer when it's in any orientation. Here's my code

public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub
    // Récupérer les valeurs du capteur
    float x, y, z;
    String s1 = "stringX", s2 = "stringY", s3 = "stringZ";

    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

        switch (mDisplay.getRotation()) {
        case Surface.ROTATION_0:
            x = event.values[0];
            y = event.values[1];
            s1 = "" + x;
            s2 = "" + y;
            break;
        case Surface.ROTATION_90:
            x = -event.values[1];
            y = event.values[0];
            s1 = "" + x;
            s2 = "" + y;
            break;
        case Surface.ROTATION_180:
            x = -event.values[0];
            y = -event.values[1];
            s1 = "" + x;
            s2 = "" + y;
            break;
        case Surface.ROTATION_270:
            x = event.values[1];
            y = -event.values[0];
            s1 = "" + x;
            s2 = "" + y;
            break;
        }
        z = event.values[2];   
        s3 = "" + z;

        tvx.setText(s1);
        tvy.setText(s2);
        tvz.setText(s3);

    }
}

I also have declared the display before the onCreate() with a

private Display mDisplay;

but i still have the javaNullPointer :s

Thank you guys.


Solution

  • You need

    mDisplay = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();