Stuck in while loop / index out of bounds exception - java

I am trying to figure out when a step occurs. So I have written a method called countSteps to do this. The problem with it is that I get stuck in it because with the while loop I keep getting new data and I don't think it ever returns back to onSensor. I also get an error called indexoutofboundsexception: invalid index 2,size 2.
So my first question is are there any other ways to implement the method I have without the while loop? Second is how can I fix the indexoutofboundsexception.
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mRotationVector;
private Sensor mAccelerometer;
private TextView mTextView4;
private TextView mTextView5;
private TextView mTextView6;
private TextView mTextView7;
private TextView mTextView8;
float a, b, c, d, x, y, z, xyz;
float[] retVals = new float[3];
float avg = 10;
float factor = (float) 1.15;
ArrayList<Float> accelData = new ArrayList<Float>();
public int peakCounter = 0;
public int underAvgCounter = 0;
public void countSteps() {
int n = 0;
float controlPoint = accelData.get(0);
while (accelData.iterator().hasNext()) {
if (accelData.get(n) != accelData.get(n + 1)) {
if (accelData.get(n) > accelData.get(n + 1)) {
if (accelData.get(n) < controlPoint) {
n++;
} else {
if (accelData.get(n) < avg * factor) {
underAvgCounter++;
}
peakCounter++;
n++;
}
} else {
controlPoint = accelData.get(n + 1);
n++;
}
} else {
n++;
}
peakCounter -= underAvgCounter;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView4 = (TextView) findViewById(R.id.textView4);
mTextView5 = (TextView) findViewById(R.id.textView5);
mTextView6 = (TextView) findViewById(R.id.textView6);
mTextView7 = (TextView) findViewById(R.id.textView7);
mTextView8 = (TextView) findViewById(R.id.textView8);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
accelData.add((float) 0);
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer,
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];
xyz = (float) Math.sqrt((x * x) + (y * y) + (z * z));
accelData.add(xyz);
mTextView7.setText("magnitude accel " + xyz);
countSteps();
mTextView8.setText("steps " + peakCounter);
}
}

while (accelData.iterator().hasNext()) {
Is always true if you have at least 1 element in collection.
accelData.iterator() creates new iterator every time,
accelData.iterator().hasNext() checks for the first element to be in collection every time
n++ is executed until end is reached and
accelData.get(n + 1) throws IndexOutOfBoundsException
One of the things you can do is to use for loop.
for (int n = 0; n < accelData.size() - 1; n++) { // size-1 is used since you're accessing n+1 index
if (accelData.get(n) != accelData.get(n + 1)) {
if (accelData.get(n) > accelData.get(n + 1)) {
if (accelData.get(n) >= controlPoint) {
if (accelData.get(n) < avg * factor) {
underAvgCounter++;
}
peakCounter++;
}
} else {
controlPoint = accelData.get(n + 1);
}
}
}
peakCounter -= underAvgCounter;

Iterator it = accelData.iterator();
while(it.hasNext()) {
float elem = it.next();
...
}

With IndexOutOfBounds, the following code code snippets is an issue:
accelData.get(n) and accelData.get(n + 1)
You are doing a check for iterator().hasNext(), but it doesnt guarantee the existence of n+1 element.
Infinite loop, I think is because you never used iterator().next() to traverse to the next element. Please refer to a simple iterator code for better understanding.
And you can use any looping techniques like for, do while, while and advanced for loops in java, it doesnt matter. All that matters is if you are doing it efficiently and its readable.

Related

infinity double operation resulting in infinity java/android studio

I'm trying to do a division (double/double) and the result is Infinity. Can someone help me and explain why that's happening?
I searched some forums, but I didn't get the answer.
I have something like that:
public class CalculoSapIsolada extends AppCompatActivity
{
double areaAcoX;
double numeroBarrasX;
double areaBarraX;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculo_sap_isolada);
//Here is where i get the value of areaBarraX
if(SapataIsolada.getAço()==50)
{
final Spinner staticSpinner = (Spinner) findViewById(R.id.spinner_diametro_aço_x);
ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter.createFromResource(this, R.array.diametro_aço_CA_50, android.R.layout.simple_spinner_item);
staticAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
staticSpinner.setAdapter(staticAdapter);
staticSpinner.setPrompt("Selecione o diâmetro da armadura");
staticSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
{
Object item = adapterView.getItemAtPosition(i);
if (i == 0) {
diametroAçoX = 0.5;
areaBarraX = 0.196;
}
if (i == 1) {
diametroAçoX = 0.63;
areaBarraX = 0.31;
}
if (i == 2) {
diametroAçoX = 0.8;
areaBarraX = 0.5;
}
if (i == 3) {
diametroAçoX = 1;
areaBarraX = 0.785;
}
if (i == 4) {
diametroAçoX = 1.25;
areaBarraX = 1.22;
}
if (i == 5) {
diametroAçoX = 1.6;
areaBarraX = 2.01;
}
if (i == 6) {
diametroAçoX = 2;
areaBarraX = 3.14;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
/* the value of areaAcoX is calculated previously and during the testrun it receives areaAcoX=11.36016 and the value of areaBarraX=0.5 */
numeroBarrasX=areaAcoX/areaBarraX;
Button calcular =(Button)findViewById(R.id.calcular_resultado);
calcular.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
//in altura.setText, areaAcoX==11.36016
TextView altura = (TextView)findViewById(R.id.alturaTotal);
altura.setText(""+areaAcoX);
//In ladoLtopo.setText, areaBarraX==0.5
TextView ladoLtopo = (TextView)findViewById(R.id.ladoL_topo);
ladoLtopo.setText(""+areaBarraX);
//In numBarrasX.setText, numeroBarrasX==Infinity
TextView numBarrasX = (TextView)findViewById(R.id.numeroBarras_x);
numBarrasX.setText(""+numeroBarrasX);
});
}
}
I have some similar operations in the code that is not shown here and I didn't get the infinity error in their value.
Dividing by 0.0 of type double yields infinity. Perhaps there's a divide by 0.0 at this line before areaBarraX has been initialized:
numeroBarrasX=areaAcoX/areaBarraX;

Timer and TimerTask with scheduleAtFixedRate causes CalledFromWrongThreadException crash when updating TextView

I'm new to Android programming. Right now, I want to update a TextView value in an Activity at a specified interval.
Car class:
public class Car {
public int Speed;
public int RPM;
public int Distance;
public int Fuel;
public Car(int Speed, int RPM, int Distance, int Fuel) {
System.out.println(
"Inisialisasi Baru"+
"\nSpeed: "+ Speed +
"\nRPM: "+ RPM +
"\nDistance: "+ Distance +
"\nFuel: "+ Fuel
);
this.Speed = Speed;
this.RPM = RPM;
this.Distance = Distance;
this.Fuel = Fuel;
}
public int getSpeed() {
return Speed;
}
public int getRPM() {
return RPM;
}
public int getDistance() {
return Distance;
}
public int getFuel() {
return Fuel;
}
}
Activity java:
TextView carSpeed, carRPM, carDistance, carFuel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mock);
carSpeed = (TextView) findViewById(R.id.carSpeed);
carRPM = (TextView) findViewById(R.id.carRPM);
carDistance = (TextView) findViewById(R.id.carDistance);
carFuel = (TextView) findViewById(R.id.carFuel);
new Timer().scheduleAtFixedRate(new TimerTask(){
Car car = new Car(20, 20, 20, 5);
#Override
public void run(){
int maxSpeed = car.Speed + 5;
int minSpeed = car.Speed - 4;
int maxRPM = car.RPM + 5;
int minRPM = car.RPM - 4;
car.Speed = new Random().nextInt((maxSpeed - minSpeed) + 1) + minSpeed;
car.RPM = new Random().nextInt((maxRPM - minRPM) + 1) + minRPM;
car.Distance += 1;
car.Fuel -= 1;
if (car.Fuel <= 0) {
car.Fuel += 20;
}
if (car.Speed <= 0) {
car.Speed = 20;
} else if (car.Speed >= 150) {
car.Speed -= 50;
}
carSpeed.setText(Integer.toString(car.getSpeed()) + " km/h");
carRPM.setText(Integer.toString(car.getRPM()) + " rpm");
carDistance.setText(Integer.toString(car.getDistance()) + " km");
carFuel.setText(Integer.toString(car.getFuel()) + " l");
}
},0,5000);
}
I think the problem happens because I'm trying to setText inside new Timer() and this cause application close. Thank you.
Yes your intuition is correct. The problem happens because the views are being updated from the timer.
The error will be similar to this:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the
original thread that created a view hierarchy can touch its views.
In Android, views can only be updated from the "UI thread" also commonly known as the "Main Thread".
The problem here is that the Runnable's run() method is being executed in a separate thread.
The updates can be done on the main thread from an Activity like this:
...
runOnUiThread(new Runnable() {
#Override
public void run() {
// Do all your view updates in here
textView.setText("string");
}
});
....
I cannot see the context of your code, but if it is a fragment:
getActivity().runOnUiThread(...);
There are also other methods for switching to the main thread. You may want to investigate AsyncTask and Handlers as well.

shared preference editor mixing up values

in my text to speech style app I can set the speed and pitch of the voice, and also 2 variables for ultrasound pitch settings. If I set the speed and pitch and exit the settings menu everything is fine, The problem is that if I press the finish button and the frequency analyzer runs and sets the ultrasound variables the variables get saved in the preference editor in the wrong spot, causing the speed and pitch to be set at the ultrasound values, I have been trying for 2 days to fix it but nothing works, below is the relevant code, if you need more please ask, can anyone see what I'm doing wrong?
EDIT: here is an apk showing the problem, go to settings menu (from toolbar upper right) set the speed and pitch, press finish, close app, open app, go to settings and you will see the ridiculous values set as speed and pitch
Canine Remote apk
Relevant initialized variables at start of class:
public SharedPreferences appPreferences;
boolean settingUp=false;
int result = 0;
int remote = 0;
int settingLanguage=0;
private float progress = (float) 1.0;
private float progress2 = (float) 1.0;
private static final String LSTYLE = "usa";//language
private static final String MYPITCH = "1.0";//normal use voice pitch
private static final String MYSPEED = "1.0";//normal use voice speed
private static final String ULTRADOG = "1.0";//22000 +/- user pitch khz
private static final String ULTRACAT = "1.0";//48000 +/- user pitch khz
private static final String HUMANDOGCAT = "0";//human=0, dog=1, cat=2
private static final String REMOTE = "0";//speak through device=0, speak
//through remote bluetooth speaker=1
private TextView edit;
private TextView edit2;
private Button edit3;
private Button edit4;
private Button edit5;
private Button edit6;
private TextView edit7;
private ImageButton edit8;
private Button edit9;
private CheckBox ckultra;
private CheckBox cklocal;
private CheckBox ckultra2;
private SeekBar cpitch;
private SeekBar cspeed;
AudioRecord mAudioRecord;
int freq = 11025;
int Nb;
int N;
int running=0;
double FreqMin = 0;
double FreqMax = 2300;
int muestras = 1000;
double PI2n = 2 * Math.PI/muestras;
double FreqMuestras=freq/muestras;
int indMin = (int) (FreqMin/FreqMuestras);
int indMax = (int) (FreqMax/FreqMuestras);
double newFrequency = 170;
double freakMin=170;
double freakMax=170;
double mean=170;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_canine_start);
appPreferences = PreferenceManager.getDefaultSharedPreferences(this);
This button sets the pitch in the preference editor
edit3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Globals g = (Globals) getApplication();
SharedPreferences.Editor editor = appPreferences.edit();
float pitch = g.getData2();
if (pitch < 0.1) pitch = (float) 0.1;
editor.putFloat(MYPITCH, pitch);
editor.commit();
tts.setPitch(pitch);
}
});
This button sets the speed in the preference editor, also I've included the slider bars and check boxes codes here if you need to see them
edit4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Globals g = (Globals) getApplication();
SharedPreferences.Editor editor2 = appPreferences.edit();
float speed=g.getData3();
if (speed < 0.1) speed = (float) 0.1;
editor2.putFloat(MYSPEED, speed);
editor2.commit();
tts.setSpeechRate(speed);
}
});
//slider bars to get pitch and speed
cpitch.setProgress(1);
edit.setText("Adjust voice Pitch: " + cpitch.getProgress());
cpitch.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
Globals g = (Globals) getApplication();
#Override
public void onProgressChanged(SeekBar cpitch, int progresValue, boolean fromUser) {
progress = (float) (progresValue * 0.1);
edit.setText("Adjust voice pitch: " + progress);
}
#Override
public void onStartTrackingTouch(SeekBar cpitch) {
}
#Override
public void onStopTrackingTouch(SeekBar cpitch) {
edit.setText("Adjust voice pitch: " + progress);
g.setData2(progress);
}
});
cspeed.setProgress(1);
edit2.setText("Adjust voice speed: " + cspeed.getProgress());
cspeed.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
Globals g = (Globals) getApplication();
#Override
public void onProgressChanged(SeekBar cspeed, int progresValue2, boolean fromUser2) {
progress2 = (float) (progresValue2 * 0.1);
edit2.setText("Adjust voice speed: " + progress2);
}
#Override
public void onStartTrackingTouch(SeekBar cspeed) {
}
#Override
public void onStopTrackingTouch(SeekBar cspeed) {
edit2.setText("Adjust voice speed: " + progress2);
g.setData3(progress2);
}
});
}
//check boxes
class clicker implements CheckBox.OnCheckedChangeListener {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
SharedPreferences.Editor editor5 = appPreferences.edit();
if (isChecked) {
if (buttonView == ckultra) {
editor5.putInt(HUMANDOGCAT, 1).commit();
ckultra2.setChecked(false);
}
if (buttonView == ckultra2) {
editor5.putInt(HUMANDOGCAT, 2).commit();
ckultra.setChecked(false);
}
if (buttonView == cklocal) {
editor5.putInt(REMOTE, 1).commit();
}
}
if (!isChecked) {
if (buttonView == ckultra) {
editor5.putInt(HUMANDOGCAT, 0).commit();
}
if (buttonView == ckultra2) {
editor5.putInt(HUMANDOGCAT, 0).commit();
}
if (buttonView == cklocal) {
editor5.putInt(REMOTE, 0).commit();
}
}
}
}
This button is the start of the code causing the error
edit6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit7.setVisibility(View.VISIBLE);
edit8.setVisibility(View.VISIBLE);
edit9.setVisibility(View.VISIBLE);
edit.setVisibility(View.GONE);
edit2.setVisibility(View.GONE);
edit3.setVisibility(View.GONE);
edit4.setVisibility(View.GONE);
edit5.setVisibility(View.GONE);
edit6.setVisibility(View.GONE);
cpitch.setVisibility(View.GONE);
cspeed.setVisibility(View.GONE);
ckultra.setVisibility(View.GONE);
ckultra2.setVisibility(View.GONE);
cklocal.setVisibility(View.GONE);
speakIT("Completed.");
Spectrometer_Start();
}
});
//analyze pitch to set ultrasound variables
public void Spectrometer_Start() {
try {
Nb = AudioRecord.getMinBufferSize(freq, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT) * 4;
N = Nb * Byte.SIZE / Short.SIZE;
mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, freq, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, Nb);
mAudioRecord.startRecording();
running=1;
analizer();
} catch (IllegalArgumentException i) {
}
}
This method saves the ultrasound settings in the wrong place in the preference editor
public void analizer() {
int a=10;
while(tts.isSpeaking())
{
a-=1;
if(a==0)
{
short[] data= new short[muestras];
try {
mAudioRecord.read(data, 0, muestras-1);
Dft(data);
} catch (Exception e) {
e.printStackTrace();
}
a=10;
}
}
mAudioRecord.stop();
mAudioRecord.release();
Globals g = (Globals) getApplication();
running=0;
mean=((freakMax-freakMin)*0.5)+freakMin;
float calcDog = (float) (22000 / mean);
float calcCat = (float) (48000 / mean);
g.setData4(calcDog);
g.setData5(calcCat);
SharedPreferences.Editor editor7 = appPreferences.edit();
editor7.putFloat(ULTRADOG, calcDog);
editor7.putFloat(ULTRACAT, calcCat);
editor7.commit();
}
public void Dft(short[] inreal) {
for (int k = indMin; k < indMax; k++)
{
float sumreal = 0;
float sumimag = 0;
float PI2kn= (float) (PI2n * k);
for (int t = 0; t < muestras; t++) {
double angle = t*PI2kn;
sumreal += inreal[t] * Math.cos(angle);
sumimag += inreal[t] * Math.sin(angle);
}
newFrequency = (Math.sqrt(sumreal * sumreal + sumimag * sumimag));
if (newFrequency < freakMin && newFrequency >= 85) {
freakMin = newFrequency;
}
if (newFrequency > freakMax && newFrequency <= 255) {
freakMax = newFrequency;
}
}
}
This button starts the speech entered, and receives the wrong values from the preference editor
edit9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String sendComands= edit7.getText().toString();
if (!sendComands.equals("") && settingLanguage == 0){
float NPITCH = appPreferences.getFloat(MYPITCH, (float) 1.0);
float NSPEED = appPreferences.getFloat(MYSPEED, (float) 1.0);
float UDOG = appPreferences.getFloat(ULTRADOG, (float) 1.0);
float UCAT = appPreferences.getFloat(ULTRACAT, (float) 1.0);
int HDC = appPreferences.getInt(HUMANDOGCAT, 0);
switch (HDC) {
case 0:
tts.setPitch(NPITCH);
break;
case 1:
tts.setPitch(UDOG);
break;
case 2:
tts.setPitch(UCAT);
break;
}
tts.setSpeechRate(NSPEED);
speakIT(sendComands);
edit7.setHint("Enter text to send");
settingUp=false;
}
if (settingLanguage == 1) {
countryC(sendComands);
settingLanguage=0;
edit7.setHint("Enter text to send");
edit9.setText("Send");
edit7.setVisibility(View.GONE);
edit9.setVisibility(View.GONE);
}
}
});
My settings menu in the toolbar with comment so you know which objects do what
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.canine_start, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Globals g = (Globals) getApplication();
int id = item.getItemId();
if (id == R.id.action_settings) {
edit.setVisibility(View.VISIBLE);//pitch slider text
edit2.setVisibility(View.VISIBLE);//speed slider text
edit3.setVisibility(View.VISIBLE);//button - set pitch
edit4.setVisibility(View.VISIBLE);//button - set speed
edit5.setVisibility(View.VISIBLE);//button - test speak
edit6.setVisibility(View.VISIBLE);//button - finished with settings
edit7.setVisibility(View.GONE);//edit text - text to speech
edit8.setVisibility(View.GONE);//image button - speech recognition start
edit9.setVisibility(View.GONE);//button - speak edit7 text
cpitch.setVisibility(View.VISIBLE);//slider - adjust voice pitch
cspeed.setVisibility(View.VISIBLE);//slider - adjust voice speed
ckultra.setVisibility(View.VISIBLE);//checkbox - ultrasound dog on/off
ckultra2.setVisibility(View.VISIBLE);//checkbox - ultrasound cat on/off
cklocal.setVisibility(View.VISIBLE);//checkbox - send to bluetooth/local device
settingUp=true;
return true;
}
Your are using invalid keys to stores your values in sharedPreferences:
These values are used as keys:
private static final String MYPITCH = "1.0";
private static final String MYSPEED = "1.0";
private static final String ULTRADOG = "1.0";
private static final String ULTRACAT = "1.0";
Here to store values
editor.putFloat(MYPITCH, pitch);
editor2.putFloat(MYSPEED, speed);
editor7.putFloat(ULTRADOG, calcDog);
editor7.putFloat(ULTRACAT, calcCat);
And here to get values
float NPITCH = appPreferences.getFloat(MYPITCH, (float) 1.0);
float NSPEED = appPreferences.getFloat(MYSPEED, (float) 1.0);
float UDOG = appPreferences.getFloat(ULTRADOG, (float) 1.0);
float UCAT = appPreferences.getFloat(ULTRACAT, (float) 1.0);
You should instead use unique and meaningful keys:
private static final String MYPITCH = "my_pitch";
private static final String MYSPEED = "my_speed";
private static final String ULTRADOG = "ultra_dog";
private static final String ULTRACAT = "ultra_cat";

Unable to hide IndexScroll from listview

I have a custom listview which is having a custom inexscroller which draws itself when you scroll through the list. Now that doesnt look nice when my listview is not having too many items. So what I want to do is to hide the IndexScroller when the items are less than a particular number to be scrollable. I have done everything but I am not able to hide the list view. Please help:
Here are the classes used:
IndexableListViewActivity
public class IndexableListViewActivity extends Activity implements OnClickListener
{
private ArrayList<String> mItems;
private IndexableListView mListView;
TextView MyTasks, TeamTasks, username, fullusername;
RelativeLayout listlay;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mItems = new ArrayList<String>();
mItems.add("Diary of a Wimpy Kid 6: Cabin Fever");
mItems.add("Steve Jobs");
mItems.add("Inheritance (The Inheritance Cycle)");
mItems.add("11/22/63: A Novel");
mItems.add("The Hunger Games");
mItems.add("The LEGO Ideas Book");
mItems.add("Explosive Eighteen: A Stephanie Plum Novel");
mItems.add("Catching Fire (The Second Book of the Hunger Games)");
mItems.add("Elder Scrolls V: Skyrim: Prima Official Game Guide");
mItems.add("Death Comes to Pemberley");
mItems.add("Diary of a Wimpy Kid 6: Cabin Fever");
mItems.add("Steve Jobs");
mItems.add("Inheritance (The Inheritance Cycle)");
mItems.add("11/22/63: A Novel");
mItems.add("The Hunger Games");
mItems.add("The LEGO Ideas Book");
mItems.add("Explosive Eighteen: A Stephanie Plum Novel");
mItems.add("Catching Fire (The Second Book of the Hunger Games)");
mItems.add("Elder Scrolls V: Skyrim: Prima Official Game Guide");
mItems.add("Death Comes to Pemberley");
mItems.add("Make this list longer");
mItems.add("A");
mItems.add("B");
// mItems.add("C");
// mItems.add("D");
// mItems.add("E");
// mItems.add("F");
// mItems.add("H");
// mItems.add("I");
// mItems.add("J");
// mItems.add("K");
// mItems.add("L");
// mItems.add("M");
// mItems.add("N");
// mItems.add("O");
// mItems.add("P");
// mItems.add("Q");
// mItems.add("R");
// mItems.add("S");
// mItems.add("T");
// mItems.add("U");
// mItems.add("V");
// mItems.add("W");
// mItems.add("X");
// mItems.add("Y");
// mItems.add("Z");
Collections.sort(mItems);
ContentAdapter adapter = new ContentAdapter(this,
android.R.layout.simple_list_item_1, mItems);
mListView = (IndexableListView) findViewById(R.id.listview);
mListView.setAdapter(adapter);
mListView.setFastScrollEnabled(true);
MyTasks = (TextView)findViewById(R.id.myTasks);
MyTasks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MyTasks.setBackgroundResource(R.drawable.rectangle_selected);
TeamTasks.setBackgroundResource(R.drawable.rectangle);
if(mListView.getLastVisiblePosition() + 1 == mListView.getCount()) {
Toast.makeText(getBaseContext(), "No need to scroll", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Need to scroll", Toast.LENGTH_SHORT).show();
}
}
});
TeamTasks = (TextView)findViewById(R.id.teamTasks);
TeamTasks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TeamTasks.setBackgroundResource(R.drawable.rectangle_selected);
MyTasks.setBackgroundResource(R.drawable.rectangle);
}
});
}
private class ContentAdapter extends ArrayAdapter<String> implements SectionIndexer {
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public ContentAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
}
#Override
public int getPositionForSection(int section) {
// If there is no item for current section, previous section will be selected
for (int i = section; i >= 0; i--) {
for (int j = 0; j < getCount(); j++) {
if (i == 0) {
// For numeric section
for (int k = 0; k <= 9; k++) {
if (StringMatcher.match(String.valueOf(getItem(j).charAt(0)), String.valueOf(k)))
return j;
}
} else {
if (StringMatcher.match(String.valueOf(getItem(j).charAt(0)), String.valueOf(mSections.charAt(i))))
return j;
}
}
}
return 0;
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
String[] sections = new String[mSections.length()];
for (int i = 0; i < mSections.length(); i++)
sections[i] = String.valueOf(mSections.charAt(i));
return sections;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
StrngMatcher.java
public class StringMatcher {
public static boolean match(String value, String keyword) {
if (value == null || keyword == null)
return false;
if (keyword.length() > value.length())
return false;
int i = 0, j = 0;
do {
int vi = value.charAt(i);
int kj = keyword.charAt(j);
if (isKorean(vi) && isInitialSound(kj)) {
} else {
if (vi == kj) {
i++;
j++;
} else if (j > 0)
break;
else
i++;
}
} while (i < value.length() && j < keyword.length());
return (j == keyword.length())? true : false;
}
private static boolean isKorean(int i) {
return false;
}
private static boolean isInitialSound(int i) {
return false;
}
}
IndexableListView.java
public class IndexableListView extends ListView {
private boolean mIsFastScrollEnabled = false;
private IndexScroller mScroller = null;
private GestureDetector mGestureDetector = null;
public IndexableListView(Context context) {
super(context);
}
public IndexableListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public IndexableListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public boolean isFastScrollEnabled() {
return mIsFastScrollEnabled;
}
#Override
public void setFastScrollEnabled(boolean enabled) {
mIsFastScrollEnabled = enabled;
if (mIsFastScrollEnabled) {
if (mScroller == null)
mScroller = new IndexScroller(getContext(), this);
}
else {
if (mScroller != null) {
mScroller.hide();
mScroller = null;
}
}
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
// Overlay index bar
if (mScroller != null)
mScroller.draw(canvas);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
// Intercept ListView's touch event
if (mScroller != null && mScroller.onTouchEvent(ev))
return true;
if (mGestureDetector == null) {
mGestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
// If fling happens, index bar shows
if(mScroller!=null)
mScroller.show();
return super.onFling(e1, e2, velocityX, velocityY);
}
});
}
mGestureDetector.onTouchEvent(ev);
return super.onTouchEvent(ev);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
#Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
if (mScroller != null)
mScroller.setAdapter(adapter);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mScroller != null)
mScroller.onSizeChanged(w, h, oldw, oldh);
}
}
IndexScroller.java
public class IndexScroller {
private float mIndexbarWidth;
private float mIndexbarMargin;
private float mPreviewPadding;
private float mDensity;
private float mScaledDensity;
private float mAlphaRate;
private int mState = STATE_HIDDEN;
private int mListViewWidth;
private int mListViewHeight;
private int mCurrentSection = -1;
private boolean mIsIndexing = false;
private ListView mListView = null;
private SectionIndexer mIndexer = null;
private String[] mSections = null;
private RectF mIndexbarRect;
private static final int STATE_HIDDEN = 0;
private static final int STATE_SHOWING = 1;
private static final int STATE_SHOWN = 2;
private static final int STATE_HIDING = 3;
public IndexScroller(Context context, ListView lv) {
mDensity = context.getResources().getDisplayMetrics().density;
mScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
mListView = lv;
setAdapter(mListView.getAdapter());
mIndexbarWidth = 20 * mDensity;
mIndexbarMargin = 2 * mDensity;
mPreviewPadding = 5 * mDensity;
}
public void draw(Canvas canvas) {
if (mState == STATE_HIDDEN)
return;
// mAlphaRate determines the rate of opacity
Paint indexbarPaint = new Paint();
indexbarPaint.setColor(Color.BLACK);
indexbarPaint.setAlpha((int) (64 * mAlphaRate));
indexbarPaint.setAntiAlias(true);
canvas.drawRoundRect(mIndexbarRect, 5 * mDensity, 5 * mDensity, indexbarPaint);
if (mSections != null && mSections.length > 0) {
// Preview is shown when mCurrentSection is set
if (mCurrentSection >= 0) {
Paint previewPaint = new Paint();
previewPaint.setColor(Color.BLACK);
previewPaint.setAlpha(96);
previewPaint.setAntiAlias(true);
previewPaint.setShadowLayer(3, 0, 0, Color.argb(64, 0, 0, 0));
Paint previewTextPaint = new Paint();
previewTextPaint.setColor(Color.WHITE);
previewTextPaint.setAntiAlias(true);
previewTextPaint.setTextSize(50 * mScaledDensity);
float previewTextWidth = previewTextPaint.measureText(mSections[mCurrentSection]);
float previewSize = 2 * mPreviewPadding + previewTextPaint.descent() - previewTextPaint.ascent();
RectF previewRect = new RectF((mListViewWidth - previewSize) / 2
, (mListViewHeight - previewSize) / 2
, (mListViewWidth - previewSize) / 2 + previewSize
, (mListViewHeight - previewSize) / 2 + previewSize);
canvas.drawRoundRect(previewRect, 5 * mDensity, 5 * mDensity, previewPaint);
canvas.drawText(mSections[mCurrentSection], previewRect.left + (previewSize - previewTextWidth) / 2 - 1
, previewRect.top + mPreviewPadding - previewTextPaint.ascent() + 1, previewTextPaint);
}
Paint indexPaint = new Paint();
indexPaint.setColor(Color.WHITE);
indexPaint.setAlpha((int) (255 * mAlphaRate));
indexPaint.setAntiAlias(true);
indexPaint.setTextSize(12 * mScaledDensity);
float sectionHeight = (mIndexbarRect.height() - 2 * mIndexbarMargin) / mSections.length;
float paddingTop = (sectionHeight - (indexPaint.descent() - indexPaint.ascent())) / 2;
for (int i = 0; i < mSections.length; i++) {
float paddingLeft = (mIndexbarWidth - indexPaint.measureText(mSections[i])) / 2;
canvas.drawText(mSections[i], mIndexbarRect.left + paddingLeft
, mIndexbarRect.top + mIndexbarMargin + sectionHeight * i + paddingTop - indexPaint.ascent(), indexPaint);
}
}
}
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
// If down event occurs inside index bar region, start indexing
if (mState != STATE_HIDDEN && contains(ev.getX(), ev.getY())) {
setState(STATE_SHOWN);
// It demonstrates that the motion event started from index bar
mIsIndexing = true;
// Determine which section the point is in, and move the list to that section
mCurrentSection = getSectionByPoint(ev.getY());
mListView.setSelection(mIndexer.getPositionForSection(mCurrentSection));
return true;
}
break;
case MotionEvent.ACTION_MOVE:
if (mIsIndexing) {
// If this event moves inside index bar
if (contains(ev.getX(), ev.getY())) {
// Determine which section the point is in, and move the list to that section
mCurrentSection = getSectionByPoint(ev.getY());
mListView.setSelection(mIndexer.getPositionForSection(mCurrentSection));
}
return true;
}
break;
case MotionEvent.ACTION_UP:
if (mIsIndexing) {
mIsIndexing = false;
mCurrentSection = -1;
}
if (mState == STATE_SHOWN)
setState(STATE_HIDING);
break;
}
return false;
}
public void onSizeChanged(int w, int h, int oldw, int oldh) {
mListViewWidth = w;
mListViewHeight = h;
mIndexbarRect = new RectF(w - mIndexbarMargin - mIndexbarWidth
, mIndexbarMargin
, w - mIndexbarMargin
, h - mIndexbarMargin);
}
public void show() {
if (mState == STATE_HIDDEN)
setState(STATE_SHOWING);
else if (mState == STATE_HIDING)
setState(STATE_HIDING);
}
public void hide() {
if (mState == STATE_SHOWN)
setState(STATE_HIDING);
}
public void setAdapter(Adapter adapter) {
if (adapter instanceof SectionIndexer) {
mIndexer = (SectionIndexer) adapter;
mSections = (String[]) mIndexer.getSections();
}
}
private void setState(int state) {
if (state < STATE_HIDDEN || state > STATE_HIDING)
return;
mState = state;
switch (mState) {
case STATE_HIDDEN:
// Cancel any fade effect
mHandler.removeMessages(0);
break;
case STATE_SHOWING:
// Start to fade in
mAlphaRate = 0;
fade(0);
break;
case STATE_SHOWN:
// Cancel any fade effect
mHandler.removeMessages(0);
break;
case STATE_HIDING:
// Start to fade out after three seconds
mAlphaRate = 1;
fade(3000);
break;
}
}
private boolean contains(float x, float y) {
// Determine if the point is in index bar region, which includes the right margin of the bar
return (x >= mIndexbarRect.left && y >= mIndexbarRect.top && y <= mIndexbarRect.top + mIndexbarRect.height());
}
private int getSectionByPoint(float y) {
if (mSections == null || mSections.length == 0)
return 0;
if (y < mIndexbarRect.top + mIndexbarMargin)
return 0;
if (y >= mIndexbarRect.top + mIndexbarRect.height() - mIndexbarMargin)
return mSections.length - 1;
return (int) ((y - mIndexbarRect.top - mIndexbarMargin) / ((mIndexbarRect.height() - 2 * mIndexbarMargin) / mSections.length));
}
private void fade(long delay) {
mHandler.removeMessages(0);
mHandler.sendEmptyMessageAtTime(0, SystemClock.uptimeMillis() + delay);
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (mState) {
case STATE_SHOWING:
// Fade in effect
mAlphaRate += (1 - mAlphaRate) * 0.2;
if (mAlphaRate > 0.9) {
mAlphaRate = 1;
setState(STATE_SHOWN);
}
mListView.invalidate();
fade(10);
break;
case STATE_SHOWN:
// If no action, hide automatically
setState(STATE_HIDING);
break;
case STATE_HIDING:
// Fade out effect
mAlphaRate -= mAlphaRate * 0.2;
if (mAlphaRate < 0.1) {
mAlphaRate = 0;
setState(STATE_HIDDEN);
}
mListView.invalidate();
fade(10);
break;
}
}
};
}
In this, IndexableListView and IndexScroller are in same package and other 2 classes are in 2 different packages.
Please help how to just hide the IndexScroller so that it doesnt show up on touches.
Since no one bothered to answer, here is the thing to be done.,
For all lines where state is set as shown in IndexScroller.java, enclose them in:
isTrue = mListView.getLastVisiblePosition() + 1 == mListView.getCount();
if(!isTrue)
{
//State Shown
}

How to elaborate 2 type of Accelerometer data

(Sorry for My bad English, I'm Italian)
I'm new in Android Programming and I have this problem:
I need the Accelerometer data (max and min value of the sqrt(x*x..)) every "1" seconds and if the absolute value of their difference (the delta) is < of 0.4*Gravity_earth, i need the data that i acquired in the previous 5 seconds of the condition, then i calculate the max value. If the value is > of THRESHOLD i flag a "non-fall" or a "fall".
Can someone solve simply this My problem?
Thank you!
this is my solution:
public class MainActivity extends Activity implements SensorEventListener{
SensorManager sm;
float acc;
private float [] sensorData;
float azimuth,pitch,roll;
float omegaMagnitude;
//ArrayList
ArrayList<Float> tutteLeAcc =new ArrayList();
ArrayList<Float> previousAcc=new ArrayList();
Iterator<Float> it;
Iterator<Float> it1;
float accMax;
float accMin;
float accPreviousMax;
float deltaAcc;
private static final String TAG = "SIMTHR";
public static final int MSG_C = 3;
public static final int MSG_D = 4;
WorkerThread mWorkerThread;
WorkerThread1 mWorkerThread1;
boolean isRunning = false;
boolean running;
Button btnStart,btnStop;
TextView txtLog;
int tt = 0;
boolean caduta;
final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_C:
//it=tutteLeAcc.iterator();
txtLog.setText("");
txtLog.append("\nAmax: "+Float.toString(accMax)+" Amin: "+Float.toString(accMin)+" dA: "+Float.toString(deltaAcc));
tutteLeAcc.clear();
break;
case MSG_D:
txtLog.append("\nPreviousACCmax: "+Float.toString(accPreviousMax)+"\n");
//previousAcc.clear();
break;
}
caduta=Detection(previousAcc,deltaAcc);
//previousAcc.clear();
}
};
class WorkerThread extends Thread {
public Handler mCallerHandler;
private int nn = 1;
public WorkerThread(Handler handler) {
mCallerHandler = handler;
Log.i(TAG,"create WorkerThread");
}
public void run() {
nn = 0;
while(running){
try {
Log.i(TAG,"WorkerThread inizia qua");
if (mCallerHandler!=null) {
accMax=trovaMax(tutteLeAcc);
accMin=trovaMin(tutteLeAcc);
deltaAcc=Math.abs(accMax-accMin);
Thread.sleep(1000);
mCallerHandler.obtainMessage(MSG_C).sendToTarget();
Log.i(TAG,"WorkerThread finisce qua");
}
} catch (InterruptedException e) {
Log.e(TAG,"errore in WorkerThread "+e.toString());
}
}
}
public synchronized void start() {
running=true;
super.start();
Log.i(TAG,"WorkerThread avviato");
}
public synchronized void cancel() {
running=false;
Log.i(TAG,"WorkerThread avviato");
}
}
class WorkerThread1 extends Thread {
public Handler mCallerHandler;
private int nn = 1;
public WorkerThread1(Handler handler) {
// salvo l'handler dei messaggi dell'activity chiamante
mCallerHandler = handler;
Log.i(TAG,"create WorkerThread1");
}
public void run() {
nn = 0;
while(running){
try {
Log.i(TAG,"WorkerThread1 inizia qua");
if (mCallerHandler!=null) {
accPreviousMax=trovaMax(previousAcc);
Thread.sleep(5000);
mCallerHandler.obtainMessage(MSG_D).sendToTarget();
Log.i(TAG,"WorkerThread finisce qua");
}
} catch (InterruptedException e) {
Log.e(TAG,"errore in WorkerThread "+e.toString());
}
}
}
// avvio del thread
public synchronized void start() {
running=true;
super.start();
Log.i(TAG,"WorkerThread avviato");
}
public synchronized void cancel() {
running=false;
Log.i(TAG,"WorkerThread avviato");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG,"Activity ONCREATE");
sm = (SensorManager)getSystemService(SENSOR_SERVICE);
sm.registerListener(this,sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_NORMAL);
sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL);
sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_NORMAL);
// oggetti della User Interface
btnStart = (Button) findViewById(R.id.btnStart);
btnStop=(Button)findViewById(R.id.btnStop);
txtLog = (TextView) findViewById(R.id.txtLog);
txtLog.setTextColor(Color.WHITE);
sensorData = new float[9];
// button per l'avvio del thread
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mWorkerThread!=null&&mWorkerThread1!=null) {
mWorkerThread.cancel();
mWorkerThread1.cancel();
mWorkerThread = null; mWorkerThread1 = null;
txtLog.append("\nrichiesto arresto THREAD 1 e 2 #"+Integer.toString(tt)+"\n");
}
tt++;
mWorkerThread = new WorkerThread(mHandler);
mWorkerThread1 = new WorkerThread1(mHandler);
mWorkerThread.start(); mWorkerThread1.start();
isRunning = true;
txtLog.append("\nrichiesto avvio THREAD 1 e 2\n");
}
});
// button per l'arresto del thread
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mWorkerThread!=null&&mWorkerThread1!=null) {
mWorkerThread.cancel();
mWorkerThread1.cancel();
mWorkerThread = null; mWorkerThread1 = null;
txtLog.append("\nrichiesto arresto THREAD 1 e 2\n");
}
isRunning = false;
}
});
}
public void Deregistra(){
sm.unregisterListener(this);
}
public void Registra(){
sm.registerListener(this,sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onSensorChanged(SensorEvent event) {
float [] values = event.values;
synchronized (this) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
sensorData[0] = event.values[0];
sensorData[1] = event.values[1];
sensorData[2] = event.values[2];
if ((sensorData[3] != 0)||(sensorData[4] != 0)||(sensorData[5] != 0)
||(sensorData[6] != 0)||(sensorData[7] != 0)||(sensorData[8] != 0))
{
float ax=sensorData[0];
float ay=sensorData[1];
float az=sensorData[2];
acc=(float) Math.sqrt((ax*ax)+(ay*ay)+(az*az));
/*
tutteLeAcc.add(acc);
accMax=trovaMax(tutteLeAcc);
accMin=trovaMin(tutteLeAcc);
deltaAcc=Math.abs(accMax-accMin);
*/
tutteLeAcc.add(acc);
previousAcc.add(acc);
}
}
else if (event.sensor.getType() == Sensor.TYPE_ORIENTATION ) {
sensorData [3] = values[0];
sensorData [4] = values[1];
sensorData [5] = values[2];
if ((sensorData[0] != 0)||(sensorData[1] != 0)||(sensorData[2] != 0)
||(sensorData[6] != 0)||(sensorData[7] != 0)||(sensorData[8] != 0))
{
azimuth=sensorData[3];
pitch=sensorData[4];
roll=sensorData[5];
}
}
else if(event.sensor.getType()==Sensor.TYPE_GYROSCOPE){
sensorData [6] = values[0];
sensorData [7] = values[1];
sensorData [8] = values[2];
final float gx=sensorData[6];
final float gy=sensorData[7];
final float gz=sensorData[8];
if ((sensorData[0] != 0)||(sensorData[1] != 0)||(sensorData[2] != 0)
||(sensorData[3] != 0)||(sensorData[4] != 0)||(sensorData[5] != 0))
{
float axisX = sensorData[6];
float axisY = sensorData[7];
float axisZ = sensorData[8];
// Calculate the angular speed of the sample
omegaMagnitude = (float) Math.sqrt((axisX*axisX) + (axisY*axisY) + (axisZ*axisZ));
}
}
}
}
public float trovaMin(ArrayList<Float> a){
Iterator<Float> it=a.iterator();
float min=a.get(0);
while(it.hasNext()){
Float x=it.next();
if(x<min){
min=x;}
}
return min;
}
public float trovaMax(ArrayList<Float> a){
Iterator<Float> it=a.iterator();
float max=a.get(0);
while(it.hasNext()){
Float x=it.next();
if(x>max){
max=x;}
}
return max;
}
public boolean Detection(ArrayList<Float> accPrec,float delta){
boolean intentional=true, static=true, lying=false;
float am;
if(delta<0.4*SensorManager.GRAVITY_EARTH){
statico=true;
Log.v("STATIC?", "yes");
if(static){
if(Math.abs(pitch)>=140||Math.abs(pitch)<30){
lying=true;
Log.v("LYING?", "yes");
if(allungato){
am=findMax(accPrec);
if(am>2.5*SensorManager.GRAVITY_EARTH||omegaMagnitude>200){
intentional=true;
Log.v("INTENTIONAL?", "yes");
}else{
intenzionale=false;
Log.v("INTENTIONAL?", "no");
}
}
}else {
lying=false;
Log.v("STANDING?", "yes");
}
}
} else {
static=false;
Log.v("STATIC?", "no");
}
if(static&&lying&&!intenional)
return true;
else return false;
}
}
There is no exact way of telling which samples are got which second. but you can approximate it by fixing frequency at which you get accelerometer updates.
Lets say we request 50 samples for second (50 hz)
for this
sm.registerListener(this,sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),50000000);
Dont use android sensor delay constants(i.e SensorManager.SENSOR_DELAY_NORMAL) they are different for different vendor devices.
Now just run a simple counter 0 to 50 (no other way :()
I hope this helps you.
my advice is to run the sensor at the maximum possible frequency:
sm.registerListener(this,sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_FASTEST);
because, any way, the rate indicated with a number is not strictly observed by the device in any case; besidesm that "numeric" rate is supported only since API v.2.3.
Then, you should write the onSensorChanged method like that.
Comment: you check if the current time is more than the latestSensorChange + DELTASENSOR (that is the number of milliseconds you want to wait between to Sensor values).
#Override
public void onSensorChanged(SensorEvent event) {
float[] values = event.values;
long Now = System.currentTimeMillis();
if (Now > (latestSensorChange + DELTASENSOR)) {
/* if ((mDbHelper.getOldVal(BreathDbAdapter.IDX_X) != values[BreathDbAdapter.IDX_X]) ||
(mDbHelper.getOldVal(BreathDbAdapter.IDX_Y)!= values[BreathDbAdapter.IDX_Y]) ||
(mDbHelper.getOldVal(BreathDbAdapter.IDX_Z)!= values[BreathDbAdapter.IDX_Z])) {
*/
msg = "Accelerometer: " + values[0]
+ ", " + values[1] + ", " + values[2] + " at " + Now + " (EndTime =" + EndTime +")";
mTextViewAccelerometer.setText(msg);
Log.v(TAG, msg );
latestSensorChange = Now;
if (Now > EndTime) {
Log.v(TAG,"Fine del Test at " + Now);
finish();
}
}
Please, let me know if it helps (sennò ti vengo a cercare perchè sono Italiano anch'io :-) )
Checco

Categories