please i am a beginner at android and i'm trying to add a CountDownTimer to my quizz , well the CountDownTimer works well and when i answer all questions in the time limit i get my results like this :
Corrects Answers : 14
Wrong Answers : 16
Score : 14/30
In case i don't catch time i get something like this :
Corrects Answers : 14
Wrong Answers : 0
Score : 14/30
Which is correct in my opinions because in that case answers are not wrong but unanswered
But if it happens that i answer all questions before the time finishes .I get the results as i want but the Count doesn't stop and keeps on running until 0 and on 0 it shows that afterward :
Corrects Answers : 0
Wrong Answers : 0
Score : 0/30
Here is the code for the timer :
mCountDownTimer = new CountDownTimer(90000, 1000) {
public void onTick(long millisUntilFinished) {
textViewtimer.setText("Seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
marks = (correct+wrong)-wrong;
Intent resultintent = new Intent(getApplicationContext(),
ResultsActivity.class);
startActivity(resultintent);
mCountDownTimer.cancel();
}
}.start();
Though i'm calling the Intent part somewhere else too to lead me to the score page
Please can anyone give me a hint or help?
I think your logic on implementing onFinish is wrong. onFinish getting called after your timer has been done or you called cancel.
You should move the mCountDownTimer.cancel(); to the last question (probably), and it will call onFinish automatically.
In your current code, your timer will be canceled only if the timer has been done, because you called cancel in the onFinish.
please use following code.
// Global variable. Put
private boolean isRunning = true;
while(isRunning)
{
textViewtimer.setText("Seconds remaining: " + millisUntilFinished / 1000);
if((millisUntilFinished / 1000) <= 0)
isRunning = false;
}
Related
So I´m writing a little egg timer for learning purpose. And actually everything works fine without that the onTick method in the CountDownTimer is only calling once at the begining and I don´t get why. Actually in the documentation it´s stated that if the action called in the method takes too long ticks can be skiped but i dont think that these calculations take longer than 60 min which is the max time usable. So the timer is ticking once like if input 30 min the display widget will show 29:59.
new CountDownTimer(timer,timer){
#Override
public void onTick(long l) {
long help = (l - (l%60000))/60000;
String help2 = "" + help;
Log.i("Minuten übrig", help2);
long help3 = (l % 60000)/1000;
String help4 = "" + help3;
Log.i("Sekunden übrig", help4);
String prov = help + ":" + help3;
display.setText(prov);
}
#Override
public void onFinish() {
button.setText("Start");
}
}.start();
Try replacing this :
new CountDownTimer(timer,timer)
with this:
new CountDownTimer(timer,1000)
You can put other value in place of 1000 but make sure it is less than timer value, else onTick will get called only once.
Also, check out Chronometer if your task is suited to this.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I use Toast.makeText to print the Number of an array. However, when I use it in a for- loop. It only printed the first number and did not do anything else.
Important: Toasts in android have two kinds of duration: Toast.LENGTH_SHORT, Toast.LENGTH_LONG however they're both slower than a duration of one loop execution or even a whole loop. So, in this case the system might print the first number and waits till the Toast disappears or overwrite all existing Toasts and print the last number or a random one.
There are several ways to handle this:
If you need to see the numbers your self, you can use :
Log.i("My Array Loop", "position: " + position + " value: " + array.get(position));
//check your Logcat for values
If you want to display them to the user using as a Toast, you can achieve this using a Handler or a Timer, but I prefer using Handler since it's more efficiante :
create a helper class for more flexibility :
public class ToastPrintHelper {
private Context context;
private ArrayList<Integer> list;
private int currentPosition = 0;
public ToastPrintHelper(Context context, ArrayList<Integer> list) {
this.context = context;
this.list = list;
}
public void printValuesEvery(final long periodInMillis) {
final Handler printHandler = new Handler();
//initialize your print runnable
Runnable printRunnable = new Runnable() {
#Override
public void run() {
//print your toast
Toast.makeText(
context,
"position :" + currentPosition + " value: " + list.get(currentPosition),
Toast.LENGTH_SHORT).show();
//repeat if there are still items to show
if (currentPosition < list.size() -1) {
currentPosition++;
//execute your runnable again but for a delay
printHandler.postDelayed(this, periodInMillis);
}
}
};
//execute your runnable without delay for the first time
printHandler.post(printRunnable);
}
}
Initialize your class this way :
ToastPrintHelper printHelper = new ToastPrintHelper(context, list);
Print values every one second (1000 millis)
printHelper.printValuesEvery(1000);
In such cases, I'd prefer using an AlertDialog with a ProgressBar and a TextView to make it more visible to the user and increase the UX/UI quality.
Note: The code was not tested, but I believe it has no errors. It can also be better simplified.
Happy Coding!
A loop that's running continuously can't execute this sort of actions on view if there's no delay. Either debug the code and see if the code is reaching every iteration number or Log the iteration numbers. Also, showing toast on every iteration is blocking your UI thread. You can use a Handler to put a delay to see the Toast and the iteration number like this:
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Show toast
Toast.makeText(this, "Iteration Number:" + i, Toast.LENGTH_SHORT).show();
//Show toast in about 5 seconds
handler.postDelayed(this, 5000);
}
}, 5000);
If I use a one minute interval as shown below, the speech function doesn't work the second time it's called. If I use a shorter, ie 30 second interval, then it works as intended. I think this has something to do with the tts engine not being ready. Any ideas? I've tested this with longer examples and the problem seems to be somewhere in the if statement. For example, I've tried 4 minute examples and it will say "4 minutes remain, 3 minutes remain, 2 minutes remain, ..., Countdown Complete".
new CountDownTimer(120000, **60000**) {
public void onTick(long millisUntilFinished) {
long minutesLeft = (((millisUntilFinished + 60000) / 1000) / 60);
if (minutesLeft==1){
speech(minutesLeft + " minute remains");
} else{
speech(minutesLeft + "minutes remain");
}
}
public void onFinish() {
speech("Countdown Complete");
}
}.start();
private void speech(String toSpeak) {
float pitch, speed;
pitch=1;
speed=1;
engine.setPitch(pitch);
engine.setSpeechRate(speed);
engine.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null, null);
}
It turns out that all I had to do was add an extra half second to my total time. So changing 120000 to 120500 fixed the problem.
I am trying to implement a CountDownTimer to post a visual text count-down until I get to 0, then send a specific message. Everything works fine until I get to 3 seconds, it calls the my done() method twice; once with 3 seconds left and once when the counter is done.
I am certain that the only time done() is called is when onFinish() in this CountDownTimer() is called. I have no clue why it is calling twice, and at consistently the same time.
My Java Code:
mainCounter = new CountDownTimer(30000, 1000){
#Override
public void onTick(long millisUntilDone){
int hours = (int) (millisUntilDone/3600000);
int mins = 0, secs = 0;
long timeLeft = millisUntilDone % 3600000;
if((int)timeLeft != 0){
mins = (int) (timeLeft/60000);
}
long timeLeftStill = timeLeft % 60000;
if((int)timeLeftStill != 0){
secs = (int) (timeLeftStill/1000);
}
((TextView)findViewById(R.id.timer_label)).setText("You have " + hours + " hours, " + mins + " mins, " + secs + " secs left");
}
#Override
public void onFinish() {
// Send Message, Out of Time
((TextView)findViewById(R.id.timer_label)).setText("MESSAGE!");
num++;
done(); //My Own Method
this.cancel();
}
}.start();
I have another counter that works perfectly, I have commented it out to ensure it doesn't affect this counter, and like I say this one works fine until I get to 3 second left.
For you problem concerning the call of onFinish() method when 3 seconds are left, you should read the answer here. Actually you should read all the answers on Android: CountDownTimer skips last onTick()! question. It will hep you understand the reason. Talking abou that thread, usually people have had problems where finish gets called approx. 1 second before the estimated time. For them it can be understood ( from the answer referenced) that at the start of every tick, before onTick() is called, the remaining time until the end of the countdown is calculated. If this time is smaller than the countdown time interval, onTick is not called anymore. But the answer there also states that there may be other processes in the background that delay the thread running CountDownTimer plus that Android itself will probably create a small delay when calling the message handler of CountDownTimer, so your undesired delay might be becauase of all that.
Few workaround have been suggested in the answers. One is either decreaseing the interval time or increasing the maximum countDownTimer value. There is also one alternative of countDownTimer method. Hope this helps you understand the possible reason and will aid you to do the workaround.
You can do like this
private int secondsLeft = 0;
private int minutes;
private int seconds;
private String timeString;
counter = new CountDownTimer(30000, 100) {
public void onTick(long ms) {
if (Math.round((float) ms / 1000.0f) != secondsLeft) {
secondsLeft = Math.round((float) ms / 1000.0f);
minutes = (secondsLeft % 3600) / 60;
seconds = secondsLeft % 60;
timeString = String.format("%02d:%02d", minutes, seconds);
textViewTimer.setText(timeString);
}
}
public void onFinish() {
textViewTimer.setText("00:00");
}
}.start();
K So i am making a timer with CountDownTimer. it is my first app i am doing and i am already running into a problem. First my timer is skipping the number 14? no clue why. and second, I dont know how to set the proper format. "mm:ss" My biggest issue is setting format. I need to have it so when i get to 8 seconds left it read 00:08 etc. and when i have minute 15 left it read 1:15, and not 00:75 or 1:75. Its been a long day trying to figure this out. Thanks in advance.
private void walk() {
new CountDownTimer(15000, 1000) {
#Override
public void onFinish() {
lapCounter++;
lapNumber.setText("Lap Number: " + lapCounter);
run();
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("Time left:" + millisUntilFinished/1000);
}
}.start();
you may want to use joda-time, see this post for details