Android repeat CountDownTimer until end foreach loop - java

I want to repeat a CountDownTimer within a for loop until its execution complete. But CountDownTimer executes first index of for loop and it can not repeat again for next index.
for (final Question questionData : questionSet) {
setUI(questionData);
startTimer();
}
private void setUI(Question questionData) {
question.setText(questionData.getQuestion());
ch1.setText(questionData.getC1());
ch2.setText(questionData.getC2());
ch3.setText(questionData.getC3());
}
private void startTimer(){
int interval = 10000;
countDownTimer = new CountDownTimer(interval, 1000) {
public void onTick(long millisUntilFinished) {
time.setText("seconds remaining: "
+ millisUntilFinished / 1000);
}
public void onFinish() {
time.setText("done!");
countDownTimer.cancel();
}
}.start();
}
Here questionSet has two index.
Thanks in advance.

Finally got a solution.
for (final Question questionData : questionSet) {
tempQuestionSet.add(questionData);
setUI(questionData);
startTimer();
break;
}
private void setUI(Question questionData) {
question.setText(questionData.getQuestion());
ch1.setText(questionData.getC1());
ch2.setText(questionData.getC2());
ch3.setText(questionData.getC3());
}
private void startTimer(){
int interval = 10000;
countDownTimer = new CountDownTimer(interval, 1000) {
public void onTick(long millisUntilFinished) {
time.setText("seconds remaining: "
+ millisUntilFinished / 1000);
}
public void onFinish() {
time.setText("done!");
final Question question = getQuestionSet();
if(question == null){
countDownTimer.cancel();
}else{
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
setUI(question);
}
});
countDownTimer.start();
}
}
}.start();
}
private Question getQuestionSet(){
Question newQuestion = null;
for (final Question questionData : questionSet) {
if(tempQuestionSet.contains(questionData)){
}
else{
tempQuestionSet.add(questionData);
return questionData;
}
}
return newQuestion;
}

Related

How can I add variable to CountDownTimer in android studio?

I'm trying to use variable into the CountDownTimer constructor but the application doesn't work. Normally works with duration without a variable(like 10000). How Can I use a variable?
my code
private CountDownTimer countDownTimer = new CountDownTimer(duration, 1000) {
#Override
public void onTick(long l) {
txt_count.setText(String.valueOf(l / 1000));
progressBar.setProgress((int) l/ 1000);
}
#Override
public void onFinish() {
iscountering = false;
if(temp_question.getQuestions().size() !=(temp_position+1))
Do_Next_Question(temp_position,temp_question);
else
Toast.makeText(ObserverRoomActivity.this, "پایان آزمون", Toast.LENGTH_SHORT).show()
}
};
private void StartTimer(){
if(!iscountering){
iscountering = true;
countDownTimer.start();
}else{
iscountering = false;
countDownTimer.cancel();
}
}
I think you need to use timer like this:
private CountDownTimer countDownTimer;
private void createTimer(int duration) {
countDownTimer = new CountDownTimer(duration, 1000) {
#Override
public void onTick(long l) {
txt_count.setText(String.valueOf(l / 1000));
progressBar.setProgress((int) l/ 1000);
}
#Override
public void onFinish() {
iscountering = false;
if(temp_question.getQuestions().size() !=(temp_position+1))
Do_Next_Question(temp_position,temp_question);
else
Toast.makeText(ObserverRoomActivity.this, "پایان آزمون", Toast.LENGTH_SHORT).show()
}
};
}
private void StartTimer(){
if(!iscountering){
iscountering = true;
countDownTimer.start();
} else {
iscountering = false;
countDownTimer.cancel();
}
}
// Call this method to pass your duration for the timer
private void createAndStartTimer(int duration) {
createTimer(duration);
startTimer();
}

How to use timer in Android

In my application i have timer for some works.
When my application running after some time my application freeze and not work any View !
In this timer every 500ms i emit socket.io
My Codes:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
socketPingTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (isSendSocketPing) {
checkSocketPingTimer += startSocketPingTimer;
if (checkSocketPingTimer == sendSocketPingTimer) {
currentTimerForSocket = System.currentTimeMillis();
try {
detailSocketUtils.getSendRTTforPing(currentTimerForSocket + "");
} catch (Exception e) {
}
}
//Show ping (from search)
Constants.currentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (isShownPing) {
detailToolbar_ping.setVisibility(View.VISIBLE);
if (checkSocketPingTimer > 500) {
detailToolbar_ping.setText(checkSocketPingTimer + "");
detailToolbar_ping.setTextColor(Color.RED);
} else {
detailToolbar_ping.setText(checkSocketPingTimer + "");
detailToolbar_ping.setTextColor(Color.GREEN);
}
} else {
detailToolbar_ping.setVisibility(View.GONE);
}
}
});
socketPing = checkSocketPingTimer;
}
}
}, 500, startSocketPingTimer);
}
});
How can i run this timers in another thread and not freeze my app ?
It should be something similar to this code:
class MyActivity extends Activity
{
private void executeLoop()
{
Handler myHandler = new Handler()
{
public void handleMessage(Message msg)
{
if (isShownPing)
{
detailToolbar_ping.setVisibility(View.VISIBLE);
if (checkSocketPingTimer > 500) {
detailToolbar_ping.setText(checkSocketPingTimer + "");
detailToolbar_ping.setTextColor(Color.RED);
} else {
detailToolbar_ping.setText(checkSocketPingTimer + "");
detailToolbar_ping.setTextColor(Color.GREEN);
}
} else
{
detailToolbar_ping.setVisibility(View.GONE);
}
}
}
socketPingTimer.scheduleAtFixedRate(new TimerTask()
{
#Override
public void run()
{
if (isSendSocketPing)
{
checkSocketPingTimer += startSocketPingTimer;
if (checkSocketPingTimer == sendSocketPingTimer) {
currentTimerForSocket = System.currentTimeMillis();
try {
detailSocketUtils.getSendRTTforPing(currentTimerForSocket + "");
} catch (Exception e) {
}
}
myHandler.sendEmptyMessage();
socketPing = checkSocketPingTimer;
}
}
}, 500, startSocketPingTimer);
}
}
private void startTimerAtFixRate() {
android.os.Handler handler = new android.os.Handler();
Runnable updateTimerThread = new Runnable() {
public void run() {
//write here whatever you want to repeat
// Like I called Log statement
// After every 1 second this below statement will be executed
Log.e("CALLED-->", "TRUE");
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(updateTimerThread, 100);
}

Delay For CountDown Timer - Android

I am making a chess clock but in it I need a delay (Like it waits 10 seconds before counting). I used a Handler for it but if the button is clicked in the 10 seconds, nothing happens. Please help! Thanks!
My code:
mHandler.postDelayed(new Runnable() {
public void run() {
// count down timer start
timer2 = new CountDownTimer(totalSeconds, Integer.parseInt(delay.getText().toString())) {
public void onTick(long millisUntilFinished) {
secondsTimer = (int) (millisUntilFinished / 1000) % 60;
minutesTimer = (int) ((millisUntilFinished / (1000 * 60)) % 60);
hoursTimer = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
person2.setText(hoursTimer + ":" + minutesTimer + ":" + secondsTimer);
}
public void onFinish() {
person2.setText("Time Up!");
person2.setBackgroundColor(Color.RED);
mp.start();
}
}.start();
}
}, finalDelay);
I want a delay but I don't want to lock the UI and make the app unresponsive as it is doing right now with the handler. Any help will be appreciated! Thanks in advance!
I think you shouldn't put CountdownTimer into Handler. You could create 2 handler instead. Here is an example.
private void startHandlerAndWait10Seconds(){
Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
public void run() {
// Start Countdown timer after wait for 10 seconds
startCountDown();
}
}, 10000);
}
private void startCountDown {
final Handler handler2 = new Handler();
handler2.post(new Runnable() {
int seconds = 60;
public void run() {
seconds--;
mhello.setText("" + seconds);
if (seconds < 0) {
// DO SOMETHING WHEN TIMES UP
stopTimer = true;
}
if(stopTimer == false) {
handler2.postDelayed(this, 1000);
}
}
});
}
If you want to start the timer immediately,
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Handler().post(new Runnable() {
public void run() {
// count down timer start
new CountDownTimer(100000, 1000) {
public void onTick(long millisUntilFinished) {
button.setText(String.valueOf(millisUntilFinished));
}
public void onFinish() {
button.setText("Time Up!");
}
}.start();
}
});
}
});
And if you want to execute it after a certain time period, then
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Handler().postDelayed(new Runnable() {
public void run() {
// count down timer start
new CountDownTimer(100000, 1000) {
public void onTick(long millisUntilFinished) {
button.setText(String.valueOf(millisUntilFinished));
}
public void onFinish() {
button.setText("Time Up!");
}
}.start();
}
}, 1000);
}
});
You can avoid using Handler starting timer immediately
private fun start10SecondsDelayTimer() {
var delayCount = 10
val timer = object : CountDownTimer(1_000_000L, 1000L) {
override fun onTick(millisUntilFinished: Long) {
if (delayCount > 0) {
delayCount--
} else {
//your calculations
}
}
override fun onFinish() {
//some calculations
}
}
timer.start()
}
but first ticks will be without your calculations

Android for loop not counting properly

So I have 3 timers. For the first one I want only to appear once, because it's something like get ready timer.
For the second and third I want to appear as many times as user wants. Before timers start user must select number of times by pressing on + or - buttons which then set value of a TextView.
That's done with this code:
int counter = 0;
homeScreenPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dodajInterval();
homeScreenMinus.setEnabled(counter > 0);
}
});
homeScreenMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oduzmiInterval();
homeScreenMinus.setEnabled(counter > 0);
}
});
}
private void oduzmiInterval() {
counter--;
brojIntervala.setText(Integer.toString(counter));
}
private void dodajInterval() {
counter++;
brojIntervala.setText(Integer.toString(counter));
}
And here's the code for timers:
public void homeScreenStart(View view) {
linearniLayoutSetup.setVisibility(View.GONE);
CountDownTimer firstCountDown = new CountDownTimer(seekBarTimerDelay.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
textViewTimerVrijeme.setText("00:00");
countDownTimerTrci();
karticaTimera.setBackgroundColor(getResources().getColor(R.color.kartica_trci));
textViewTimerTrciHodajBlaBla.setText(getResources().getString(R.string.timer_trci));
}
}.start();
}
public void countDownTimerTrci() {
for (int i = 0; i < counter; i++) {
toolbar.setBackgroundColor(getResources().getColor(R.color.kartica_trci));
CountDownTimer secondCountDown = new CountDownTimer(seekBarIntervaliVisokogIntenziteta.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
textViewTimerVrijeme.setText("00:00");
karticaTimera.setBackgroundColor(getResources().getColor(R.color.kartica_hodaj));
imageViewTimerSlika.setImageResource(R.drawable.ic_timer_niski_intenzitet);
textViewTimerTrciHodajBlaBla.setText(getResources().getString(R.string.timer_hodaj));
toolbar.setBackgroundColor(getResources().getColor(R.color.kartica_hodaj));
CountDownTimer thirdCountDown = new CountDownTimer(seekBarIntervaliNiskogIntenziteta.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
textViewTimerVrijeme.setText("00:00");
countDownTimerTrci();
}
}.start();
}
}.start();
}
}
As you can see, it's a method which is called when button is pressed and I wan't first timer to appear only once and that's why I didn't include it in foor loop.
First timer shows only once and that works, but other two timers keep repeating until I close the app.
Can someone tell me where the problem is?
Try this ,replace your countDownTimerTrci method with mine
public void countDownTimerTrci() {
if(counter>0) {
toolbar.setBackgroundColor(getResources().getColor(R.color.kartica_trci));
CountDownTimer secondCountDown = new CountDownTimer(seekBarIntervaliVisokogIntenziteta.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
textViewTimerVrijeme.setText("00:00");
karticaTimera.setBackgroundColor(getResources().getColor(R.color.kartica_hodaj));
imageViewTimerSlika.setImageResource(R.drawable.ic_timer_niski_intenzitet);
textViewTimerTrciHodajBlaBla.setText(getResources().getString(R.string.timer_hodaj));
toolbar.setBackgroundColor(getResources().getColor(R.color.kartica_hodaj));
CountDownTimer thirdCountDown = new CountDownTimer(seekBarIntervaliNiskogIntenziteta.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
counter--;
textViewTimerVrijeme.setText("00:00");
countDownTimerTrci();
}
}.start();
}
}.start();
}
}

problem with stopWatch in android

in my app i have placed a stop watch with two buttons. The stop watch works in a proper way. But the problem is at start the timer looks as 0:0:0, when it starts counting the single digits are been changed over to double digits as 0:12:53.
this affects and disturbs the other layers too. At the start itself i want it to be displayed as 00:00:00 by default, so that i cant make changes in the layout.
but i don't know where to give the value for this. Following is my code
b1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(b1.getText().toString().equals("Start"))
{
if(currentThread.getState()==Thread.State.NEW)
{
currentThread.start();
shouldRun = true;
b1.setText("Stop");
}
else
{
shouldRun = false;
b1.setText("Stop");
}
}
else if(b1.getText().toString().equals("Stop"))
{
time=0;
time1=0;
time2=0;
}
}
});
b2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(b2.getText().toString().equals("Pause"))
{
shouldRun = false;
b2.setText("Resume");
}
else if(b2.getText().toString().equals("Resume"))
{
shouldRun = true;
b2.setText("Pause");
}
}
});
}
#Override
public void run()
{
try
{
while(true)
{
while(shouldRun)
{
Thread.sleep(1000);
Log.e("run", "run");
threadHandler.sendEmptyMessage(0);
}
}
}
catch (InterruptedException e) {}
}
private Handler threadHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
sec=time2++;
if(sec == 59)
{
time2=0;
sec = time2++;
min=time1++;
}
if(min == 59)
{
time1=0;
min = time1++;
hr=time3++;
}
stopWatch.setText(""+hr+":"+min+":"+sec);
}
};
}
how to do this please help me............
This should do the work:
String time = String.format("%02d:%02d:%02d", hr, min, sec);
stopWatch.setText(time);
Or the one-line-version:
stopWatch.setText(String.format("%02d:%02d:%02d", hr, min, sec));
set the text like so
stopWatch.setText(""+(hr<10?"0"+hr:hr)+":"+(min<10?"0"+min:min)+":"+(sec<10?"0"+sec:sec));
will:
stopWatch.setText("00:00:00");
not do the trick when you initialise it?
It's simple you just add this code
private Handler threadHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
sec=time2++;
if(sec == 59)
{
time2=0;
sec = time2++;
min=time1++;
if(sec< 10)
sec= "0"+sec
}
if(min == 59)
{
time1=0;
min = time1++;
hr=time3++;
if(min< 10)
min= "0"+min
}
if(hr< 10)
hr= "0"+hr
stopWatch.setText(""+hr+":"+min+":"+sec);
}
};

Categories

Resources