I'm developing an android app and I have a problem with the chronometer. And when the onChronometerTick method gets called, on the 60th second the TextView should get updated, but it gets updated on the 58th second the first time. And if you pause and start the chronometer again it gets updated at a diferent time. I found that the onChronometerTick method gets called twice when I start the chronometer and that is where my problem comes from! Can someone help me? Thanks!
Here is my code:
int br = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bProg = (Button) findViewById(R.id.bProgram);
bProg.setOnClickListener(this);
tv = (TextView) findViewById(R.id.textView1);
chrono = (Chronometer) findViewById(R.id.chronometer);
chrono.setBase(SystemClock.elapsedRealtime());
chrono.setOnChronometerTickListener(this);
chrono.stop();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bProgram:
Log.d(TAG, "bProgram Clicked");
checkButton();
// Change the electricity consumption for the given program
changeConsumption();
calculateSecondPrice();
tvCons.setText(String.valueOf(consumption * 1000 + " W"));
tvPrice.setText(String.valueOf(price + " lv."));
if (prog > 0) {
startChronometer();
}
if (prog == 0) {
pauseChronometer();
}
break;
}
}
private void pauseChronometer() {
timeWhenStopped = chrono.getBase() - SystemClock.elapsedRealtime();
chrono.stop();
}
private void startChronometer() {
if (prog == 1) {
chrono.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
chrono.start();
}
}
@Override
public void onChronometerTick(Chronometer chronometer) {
br++;
totalPrice += secondPrice;
if (br == 60) {
br = 0;
tv.setText(String.valueOf((double) (totalPrice) / 1000000));
}
}
}