Repeat specific action X number of times in Android - java

So I want certain action to be performed X number of times, depends on how many times user wants it. User selection will be selected from a TextView string which is set up with this code:
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));
}
Those are basicly two buttons that increment or decrement value of TextView.
The action I want to perform X times is this:
public void homeScreenStart(View view) {
linearniLayoutSetup.setVisibility(View.GONE);
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();
}
private void countDownTimerTrci() {
toolbar.setBackgroundColor(getResources().getColor(R.color.kartica_trci));
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));
countDownTimerHodaj();
}
}.start();
}
private void countDownTimerHodaj(){
toolbar.setBackgroundColor(getResources().getColor(R.color.kartica_hodaj));
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");
karticaTimera.setBackgroundColor(getResources().getColor(R.color.colorAccent));
textViewTimerTrciHodajBlaBla.setText("Done!");
}
}.start();
}
So it is combination of 3 seekbars, or timers, one running after another and then they should run as many times as user selects.
The problem is, I have no idea how to set this up, and I need that first block of code in timers to run just once, and those 2 methods below it to run X times.
How can I do it?

Unless I am missing something couldn't you just wrap your code in the action in a loop that references the current counter? You may need to block input so that the user can not modify the counter (unless you want them to) after execution has begun but that should be it.
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));
}
}
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));
countDownTimerHodaj();
}
}
CountDownTimer thirdCountDown = 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));
countDownTimerHodaj();
}
}
for (int i = 0; i < counter; i++) {
firstCountDown.start();
toolbar.setBackgroundColor(getResources().getColor(R.color.kartica_trci));
secondCountDown.start();
thirdCountDown.start();
}
}
Should work for you

Related

How To Destroy CoundownTimer in Java when the button is pressed?

I make a timer with a count time of 5 seconds, then when I press the exit button the counter automatically stops?
Here is my timer code:
public void startTimer(final long finish, long tick) {
CountDownTimer t;
t = new CountDownTimer(finish, tick) {
public void onTick(long millisUntilFinished) {
long remainedSecs = millisUntilFinished / 1000;
textTimer.setText("" + (remainedSecs / 60) + ":" + (remainedSecs % 60));// manage it accordign to you
}
public void onFinish() {
textTimer.setText("00:00");
Toast.makeText(FloatingVideoWidgetShowService.this, "Waktu Habis", Toast.LENGTH_SHORT).show();
long seek = videoView.getCurrentPosition();
videoView.setKeepScreenOn(false);
stopSelf();
WritableMap args = new Arguments().createMap();
args.putInt("index", index);
args.putInt("seek", (int) seek);
args.putString("url", playingVideo.getString("url"));
args.putString("type", "close");
sendEvent(reactContext, "onClose", args);
onDestroy();
cancel();
}
}.start();
}
And this is my code when pressing the stop / exit button :
floatingWindow.findViewById(R.id.btn_deny).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
long seek = videoView.getCurrentPosition();
videoView.setKeepScreenOn(false);
stopSelf();
WritableMap args = new Arguments().createMap();
args.putInt("index", index);
args.putInt("seek", (int) seek);
args.putString("url", playingVideo.getString("url"));
args.putString("type", "close");
sendEvent(reactContext, "onClose", args);
onDestroy();
}
});
How so when btn_deny is clicked Cuntdowntimer stops and does not force close?
Thanks.
You can't use onDestroy() to close your activity or fragment. Instead, you need to call finish().
To close the CountDownTimer, you need to make it a class scope variable. Prepare the timer at your startTimer then stop the timer by calling t.cancel() like the following code:
public class YourActivity extends Activity {
// Declare the variable to be accessed later.
CountDownTimer t;
...
public void startTimer(final long finish, long tick) {
t = new CountDownTimer(finish, tick) {
...
}.start();
}
private void yourOtherMethod() {
floatingWindow.findViewById(R.id.btn_deny).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(t != null) t.cancel();
...
}
});
}
}

android - start an activity onTouch

In my app I have a countdown which counts from five to one. At the moment, the counter starts as soon as the activity is started. What I want is to stay at 5 seconds and wait to count down until the screen is touched. So the countdown timer should be started which a touch event.
public class MainActivity extends Activity implements OnGestureListener {
private static final String FORMAT = "%02d:%02d";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
new CountDownTimer(5000, 10) {
public void onTick(long millisUntilFinished) {
text.setText("" + String.format("%02d:%03d",
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)),
TimeUnit.MILLISECONDS.toMillis(millisUntilFinished) - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished))
));
if (animationRunning) {
cancel();
}
}
public void onFinish() {
text.setText("done!");
}
}.start();
}
#Override
public boolean onTouchEvent(MotionEvent touchevent) {
}
}
Place your count down timer inside onTouch like below
public class MainActivity extends Activity implements OnGestureListener {
private static final String FORMAT = "%02d:%02d";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
}
#Override
public boolean onTouchEvent(MotionEvent touchevent) {
new CountDownTimer(5000, 10) {
public void onTick(long millisUntilFinished) {
text.setText("" + String.format("%02d:%03d",
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)),
TimeUnit.MILLISECONDS.toMillis(millisUntilFinished) - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished))
));
if (animationRunning) {
cancel();
}
}
public void onFinish() {
text.setText("done!");
}
}.start();
}
}
Move this section of code to your onTouchEvent, because it's on activity create that is why its starting when your activity starts
new CountDownTimer(5000, 10) {
public void onTick(long millisUntilFinished) {
text.setText("" + String.format("%02d:%03d",
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)),
TimeUnit.MILLISECONDS.toMillis(millisUntilFinished) - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished))
));
if (animationRunning) {
cancel();
}
}
public void onFinish() {
text.setText("done!");
}
}.start();
you should be fine

reset downcounter in android

I am trying to run the downcounter in a loop that is after 5seconds the counter starts counting again from 5 to 0.
I have tried this code
countDownTimer.cancel();
countDownTimer.start();
bt this does not work. The value in textview does not reset. Posted below is the complete code.
Regards!
private void timee() {
for (int j = 5; j > 0; j--) {
countDownTimer = new MalibuCountDownTimer(5000, 1000);
if (j == 4)
countDownTimer.start();
else {
countDownTimer.cancel();
countDownTimer.start();
}
}
}
// CountDownTimer class
public class MalibuCountDownTimer extends CountDownTimer {
public MalibuCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_SHORT).show();
// takeImage();
}
#Override
public void onTick(long millisUntilFinished) {
tt.setText("Time remain:" + millisUntilFinished / 1000);
}
}
Replace your timee() method and CountDownTimer class with following code
private void timee(){
MalibuCountDownTimer countDownTimer=new MalibuCountDownTimer(5000, 1000);
countDownTimer.start();
}
public class MalibuCountDownTimer extends CountDownTimer {
public MalibuCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_SHORT).show();
j++;
if(j<=5)
start();
}
#Override
public void onTick(long millisUntilFinished) {
m_tv_emp.setText("Time remain:" + millisUntilFinished / 1000);
}
}
note: take j as class varieble

restart or refresh a timer when button is clicked in android [duplicate]

This question already has an answer here:
Restart Countdown Timer with new time android
(1 answer)
Closed 8 years ago.
how to restart a timer in every button click? here given a sample code for timer setting
new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
//getSelectedAlphabet.setText(selectedIndex.getText());
}
public void onFinish() {
//mTextField.setText("done!");
getSelectedAlphabet.setVisibility(View.INVISIBLE);
Log.d("Counter", "Finished....");
}
}.start();
Try this
CountDownTimer cdt;
cdt = new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
//getSelectedAlphabet.setText(selectedIndex.getText());
}
public void onFinish() {
//mTextField.setText("done!");
getSelectedAlphabet.setVisibility(View.INVISIBLE);
Log.d("Counter", "Finished....");
}
}.start();
// to restart
cdt.cancel(); // to cancel
cdt.start(); //to start
final CountDownTimer remainingTimeCounter = new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
Log.d("Counter", "Finished....");
}
}.start();
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
remainingTimeCounter.cancel();
remainingTimeCounter.start();
}
});
final CounterClass timer = new CounterClass(180000,1000);
button.setOnclickListener(new OnClickListener() {
#Override
public void onClick(View view) {
timer.start();
}
};
CounterClass-
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
System.out.println("finished");
}
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
}
}

Nesting countdown timers in android

I want call CountDownTimer when one countdownTimer finishes it's execution.I tried calling one countdowntimer from another countdown timer's onFinish() method but it giving me nullpointer exception when I run this code.
public void First_Timer(){
Timer_Off =false;
dialog = new Dialog(context,android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
dialog.setCancelable(false);
dialog.setContentView(R.layout.backwash_timer_dialog);
final ToggleButton togglebtn_BW_timer = (ToggleButton)dialog.findViewById(R.id.togglebtn_BW_timer);
final ProgressBar bar = (ProgressBar)dialog.findViewById(R.id.progressBar1);
textView1 = (TextView)dialog.findViewById(R.id.textView1);
btn_BW_timer_stop = (Button)dialog.findViewById(R.id.btn_BW_timer_stop);
/** CountDownTimer starts with 2 minutes and every onTick is 1 second */
cdt = new CountDownTimer(twoMin, 1000) {
public void onTick(long millisUntilFinished) {
bar.setProgress((int) ((millisUntilFinished / 1000) ));
messageHandler.sendMessage(Message.obtain(messageHandler,(int) ((millisUntilFinished / 1000) ) ));
}
public void onFinish(){
textView1.setText("Time Up! ");
cdt.cancel();
Timer_Off =true;
dialog.dismiss();
// Call Second Timer Here
Second_Timer();
}
}.start();
btn_BW_timer_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
cdt.cancel();
bar.setProgress(0);
textView1.setText("0");
Timer_Off=true;
dialog.dismiss();
//onBackwashStopped();
}
});
dialog.show();
}
And Code for another timer is,
public void Second_Timer(){
Timer_Rinse_Off =false;
dialog_Rinse = new Dialog(context,android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
dialog_Rinse.setCancelable(false);
dialog_Rinse.setContentView(R.layout.rinse_timer_dialog);
final ProgressBar bar = (ProgressBar)dialog.findViewById(R.id.progressbar_Rinse);
txtRinse_TimerVal = (TextView)dialog.findViewById(R.id.txtRinse_TimerVal);
btn_Rinse_timer_stop = (Button)dialog.findViewById(R.id.btn_Rinse_timer_stop);
/** CountDownTimer starts with 2 minutes and every onTick is 1 second */
cdt_Rinse = new CountDownTimer(twoMin, 1000) {
public void onTick(long millisUntilFinished) {
bar.setProgress((int) ((millisUntilFinished / 1000) ));
messageHandler.sendMessage(Message.obtain(messageHandler,(int) ((millisUntilFinished / 1000) ) ));
}
public void onFinish(){
txtRinse_TimerVal.setText("Time Up! ");
Timer_Rinse_Off =true;
dialog_Rinse.dismiss();
}
}.start();
btn_Rinse_timer_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
cdt_Rinse.cancel();
bar.setProgress(0);
txtRinse_TimerVal.setText("0");
Timer_Rinse_Off=true;
dialog_Rinse.dismiss();
//onBackwashStopped();
}
});
dialog_Rinse.show();
}

Categories