Search code examples
androidtextviewandroid-sensors

updating Textview based on sensordata


I'm trying to update a textview based on sensorinput - more precise pitch. I have no problem getting the sensor data, converting it to degrees and displaying it in a textview. The problem is, that I wan't different numbers displayed, based on the pitch in degrees. I have written a if-else if statement and placed it in the onsensorchanged, but apart from the initial number it does not update.

     @Override


public void onSensorChanged(SensorEvent event) {

  switch(event.sensor.getType()){
  case Sensor.TYPE_ACCELEROMETER:
   for(int i =0; i < 3; i++){
    valuesAccelerometer[i] = event.values[i];
   }
   break;
  case Sensor.TYPE_MAGNETIC_FIELD:
   for(int i =0; i < 3; i++){
    valuesMagneticField[i] = event.values[i];
   }
   break;
  }

  boolean success = SensorManager.getRotationMatrix(
       matrixR, 
       matrixI, 
       valuesAccelerometer, 
       valuesMagneticField);

  if(success){
   SensorManager.getOrientation(matrixR, matrixValues);

// Float to double
   double pitch = Math.toDegrees(matrixValues[1]);
// 1 decimal
    pitch = Math.abs(round(pitch, 0));

//set textview vinkel to degrees
  vinkel.setText(String.valueOf(pitch));

// find tubesize from edittext
  String tubesizestring = tubesize.getText().toString();



  if(tubesizestring=="1000"){

      if(pitch>=0.6){
          kwh.setText("2,69");
      }else if(pitch>=1.0){
          kwh.setText("3,47");
      }else if(pitch>=2.0){
          kwh.setText("4,90");
      }else if(pitch>=5.0){
          kwh.setText("7,75");
      }else if(pitch>=10.0){
          kwh.setText("10,96");
      }else if(pitch>=20.0){
          kwh.setText("15,50");
      }else if(pitch>=30.0){
          kwh.setText("18,99");
      }else{
          kwh.setText("more than 30 degrees");

      }
  }
  }

I hope it is clear what I'm trying to do. Othervise please ask

Hope somebody can point me in the right direction


Solution

  • It doesn't work because your logic is fundamentally flawed. Let's assume the pitch is around 25. It's greater than 0.6 and 1.0 and so on. So obviously only the first if statement will be seen, since the others are else if statements. To get it to work, change the order of the statements.

        if(pitch>=30.0){
          kwh.setText("18,99");
      }else if(pitch>=20.0){
          kwh.setText("15,50");
      }else if(pitch>=10.0){
          kwh.setText("10,96");
      }else if(pitch>=5.0){
          kwh.setText("7,75");
      }else if(pitch>=2.0){
          kwh.setText("4,90");
      }
    else if(pitch>=1.0){
          kwh.setText("3,47");
      }
      else if(pitch>=0.6){
          kwh.setText("2,69");
      }eelse{
          kwh.setText("more than 30 degrees");