Reputation: 317
Here is my problem:
I get user input from two numberPickers. I then use the collected number to set the millisInFuture
of my countdown timer. But the problem is: whatever number I choose, the millisUntilFinished
of my countdown timer would not change according to user input.
My code is simplified as follows:
int firstMin = 1;
int firstSec = 30;//initial value in the field
int i = 1; //to determine whether the remained time should be shown
private void initFirstMinPicker() {
minPicker.setMaxValue(60);
minPicker.setValue(firstMin);//set the current value of number picker
minPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
firstMin = newVal;//pass the selected int to firstMin
}
});
//My countdown timer is supposed to start on clicking a button
firstTimer = new CountDownTimer(firstMin * 60000, 500) {//use 500 to
avoid skipping the last onTick()
@Override
public void onTick(long millisUntilFinished) {
Log.d("TAG", "onTick:firstMin " + firstMin);
if (i % 2 == 0) {
workLeft.setText(String.valueOf(millisUntilFinished / 1000));
}
i++;
}
@Override
public void onFinish() {
}
};
My TAG:
D/TAG: onTick:firstMin 6
D/TAG: onTick:firstMin 6
D/TAG: onTick:firstMin 6
It's clear that firstMin
has been changed, but when I use firstMin * 60000
as an argument, the millisUntilFinished
will always start from 60000 regardless of how much firstMin * 60000
evaluates to. That is, when my countdown timer begins to count down, it always count downwards from 60(initial value of firstMin * 60). I have no idea why this should happen. Have you guys ever come across such a problem? Any help would be very much appreciated.
Upvotes: 0
Views: 95
Reputation: 10270
You are only declaring firstTimer
once, meaning that it'll only ever be created when firstmin = 1
. You'll need to create a new instance of firstTimer
whenever onValueChanged
is called, for example:
minPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
firstMin = newVal;//pass the selected int to firstMin
firstTimer = new CountDownTimer(firstMin * 60000, 500) { ... }
}
});
It might also be worth creating a function that returns a new CountDownTimer
, taking only the value of firstMin
and automatically populating the rest of the default values, to save on unnecessary code repetition.
Upvotes: 2