I am using the following class to read accelerometer data from an android mobile:
public class AccelerometerData extends Activity implements SensorEventListener {
//variables
public AccelerometerData()
{
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO: my codes
}
}
}
Now from my main activity class, I was calling that class to read the data
AccelerometerData sbt = new AccelerometerData ();
and it shows the following message Unfortunately AccelerometerData has stopped. I am new in android development and not sure what is wrong here.
Any help would be highly appreciated.
The answer you're looking for might look a little something like this. The MainActivity owns the AccelerometerData class.
public class MainActivity extends Activity {
priavte AccelerometerData ad;
private TextView someTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// "this" allows 'ad' to make calls back to the MainActivity
ad = new AccelerometerData((SensorManager)getSystemService(SENSOR_SERVICE), this);
someTextView = (TextView)findViewById(R.id.my_text_view);
}
protected void onResume() {
super.onResume();
sensorHandler.onResume();
}
protected void onPause() {
super.onPause();
sensorHandler.onPause();
}
protected void setTextViewValue(float[] values){
someTextView.setText( Float.toString(values[0]) );
}
Then in AccelerometerData class it might look something like this.
public class AccelerometerData implements SensorEventListener {
private final SensorManager mSensorManager;
private final Sensor mAccelerometer;
private final MainActivity ma;
public AccelerometerData(SensorManager sm, MainActivity ma){
mSensorManager = sm;
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
this.ma = ma
}
protected void onResume() {
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
mSensorManager.unregisterListener(this);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
// Here we call a method in MainActivity and pass it the values from the SensorChanged event
ma.setTextViewValue( event.values );
}
}
Your class shouldn't extend Activity. It doesn't need to. It should be owned by an activity of some sort instead.