I'm writing an app that show accelerometer readings, I was able yesterday to write all the accelerometer code in the main activity and it works fine on emulator and my device.
But today I was trying to make a class that contains all the accelerometer code and return the three integers X,Y,Z in integer array only, so I make a code that I think it`s right but every time I run the project on the emulator and it always give me 0 ,0,0 . So I wish any help , please .
activity code ::
package com.example.accelerometer_sensor;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
int [] AccVal = new int[3];
TextView acceleration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AccelerometerClass acc = new AccelerometerClass();
acc.AccelerometerInit(this);
AccVal =acc.Vals;
acceleration = (TextView)findViewById(R.id.acceleration);
acceleration.setText("X: "+acc.Vals[0]+
"\nY: "+acc.Vals[1]+
"\nZ: "+acc.Vals[2]);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
accelerometerClass :
package com.example.accelerometer_sensor;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class AccelerometerClass implements SensorEventListener
{
int [] Vals = new int[3];
Sensor accelerometer;
SensorManager sm;
public void AccelerometerInit(Context context)
{
sm = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
accelerometer=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelerometer,SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onResume() {
sm.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
sm.unregisterListener(this);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
Vals[0]=(int)event.values[0];
Vals[1]=(int)event.values[1];
Vals[2]=(int)event.values[2];
}
}
please i stuck in this problem for along time , any help will be appreciate .