Search code examples
javaandroideclipseaccelerometerlogcat

Unexpected Crash Android Sensors


Whenever I try to run this it crashes. I do not know where the problem could be. Am I missing something or is something in the wrong place?In the logcat it says the system services are not avaliable to activities before oncreate.

import android.os.Bundle;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.view.Menu;
import android.widget.*;
import android.*;

import java.math.*;
import java.text.*;
import java.util.*;

public class MainActivity extends Activity implements SensorEventListener {


    private final SensorManager mSensorManager;
    private final Sensor mRotationVector;

    public float x,y,z;

    public MainActivity(){
            mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
            mRotationVector = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mRotationVector, SensorManager.SENSOR_DELAY_GAME);
    }

    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }

    @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) {
        x= event.values[0];
        y= event.values[1];
        z= event.values[2];

        TextView mTextView0 = (TextView) findViewById(R.id.textView0);
        mTextView0.setText("x"+x);
        TextView mTextView1 = (TextView) findViewById(R.id.textView1);
        mTextView1.setText("y"+y);
        TextView mTextView2 = (TextView) findViewById(R.id.textView2);
        mTextView2.setText("z"+z);


    }

}

Solution

  • system services are not avaliable to activities before oncreate
    

    Your LogCat telling you the everything !

    So change to

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        mRotationVector = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
    }
    

    and remove this constructor public MainActivity().