Search code examples
javaandroidaccelerometerandroid-sensors

Can't get app to update based on accelerometer data in Android Studio


I am trying to clear the text labels/output when the phone is shaken by using accelerometer data.

This is what I have:

imports ....
public class Main_Activity extends AppCompatActivity implements TextToSpeech.OnInitListener, SensorEventListener{

    public void onAccuracyChanged(Sensor arg0, int arg1){

    }

    public void onSensorChanged(SensorEvent event){

        double ax = event.values[0];
        double ay = event.values[1];
        double az = event.values[2];
        double a = Math.sqrt(ax*ax + ay*ay + az*az);

        if(a > 20){
            ((EditText) findViewById(R.id.pBox)).setText("");
            ((EditText) findViewById(R.id.aBox)).setText("");
            ((EditText) findViewById(R.id.iBox)).setText("");
            ((TextView) findViewById(R.id.output)).setText("");
        }


    public void buttonClicked(View v){
        // getting values entered by user and showing output
    }
}

Everything works except when I shake my phone, the text doesn't clear.


Solution

  • Please create these as global var

    private float acelVal,acelLast,shake;
    

    Please use this login to get shake events in your onSensorChanged()

    float x =event.values[0];
    float y =event.values[1];
    float z =event.values[2];
    acelLast=acelVal;
    acelVal=(float) Math.sqrt((double) (x*x)+(y*y)+(z*z));
    float delta= acelVal-acelLast;
    shake =shake*0.9f+delta;
    
    
    if(shake>20){
        ((EditText) findViewById(R.id.pBox)).setText("");
        ((EditText) findViewById(R.id.aBox)).setText("");
        ((EditText) findViewById(R.id.iBox)).setText("");
        ((TextView) findViewById(R.id.output)).setText("");
    }
    

    This is the original answer

    Hope this will help!