0

I'm a beginner at coding. Basically, i'm building a speedometer app. I want to set a few conditions; if the speed is below 5km/h, the background will be green, if the speed is between 5km/h to 9km/h, the background will be yellow, and finally; when the speed is above 10km/h, the background will be red, there will be an alert which activates for 4 seconds with an interval of 5 seconds.

Right now, when the speed reaches 10 and above, the alert keeps on playing with no intervals, and after a few seconds the app crashes. I'm wondering if anyone could help figure out this problem and help me out with writing the correct codes to implement. Thank you.

@Override
public void onLocationChanged(Location location) {
    //for alert
    alert2 = MediaPlayer.create(this, R.raw.car_alarm);
    CountDownTimer Timer = new CountDownTimer(4000, 4000) {
        public void onTick(long millisUntilFinished) {
        }

        public void onFinish() {
            if (alert2.isPlaying()) {
                alert2.stop();
                alert2.release();
            }
        }
    };
    Timer.start();

    if (location == null) {
        speedo.setText("-.- km/h");
    } else {
        currentSpeed = location.getSpeed() * 1.85f; //Knots to kmh conversion.
        speedo.setText(Math.round(currentSpeed) + " km/h");
    }
    if (currentSpeed <=4.99) {
        background.setBackgroundColor(Color.GREEN);
        alert2.stop();

    } else if (currentSpeed >=5.00 && currentSpeed <=9.99) {
        background.setBackgroundColor(Color.YELLOW);
        alert2.stop();

    } else if (currentSpeed >=10.00) {
        background.setBackgroundColor(Color.RED);
        alert2.start();
    }
}
mlwn
  • 1,156
  • 1
  • 10
  • 25
DBiscuits
  • 3
  • 2
  • Does this answer your question? [Unfortunately MyApp has stopped. How can I solve this?](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) – a_local_nobody Mar 19 '20 at 17:13
  • not marking this as a complete duplicate, this is just relevant to you to help debug in future :) – a_local_nobody Mar 19 '20 at 17:14

1 Answers1

0

the alert keeps on playing with no intervals, and after a few seconds the app crashes.

Nope, it's not the case. But you are launching a timer every time the location has changed ! So, you have many timer launched in parallel.

You have to externalize your Timer. Same remark for alert2 : you don't have to recreate it ! Just create it ones and reuse it.

Bruno
  • 3,872
  • 4
  • 20
  • 37