How can i reset the timer if my button is clicked? - java

I have a textview and i made a timer to decrease from 45 seconds to 0
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_password);
TextView textView = (TextView) findViewById(R.id.textView6);
t1 = (TextView)findViewById(R.id.t1);
b1 = (Button) findViewById(R.id.button1);
new CountDownTimer(45000, 1000) {
public void onTick(long millisUntilFinished) {
t1.setText("00:" + millisUntilFinished / 1000);
if(millisUntilFinished<=10000){
t1.setText("00:0" + millisUntilFinished / 1000);
}
}
public void onFinish() {
t1.setText("Tempo acabado");
b1.setEnabled(true);
}
}.start();
I want after the time has expired give the option for the user to click the b1 button and restart the timer

You can create instance of CountDownTimer, then when you need to restart you can perform cancel and start on that instance.
CountDownTimer countDownTimer = new CountDownTimer(45000, 1000) {
//......................
}
//Start at first
countDownTimer.start();
//Restart when button is pressed
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
countDownTimer.cancel();
countDownTimer.start();
}
});

Is this what you want?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_password);
TextView textView = (TextView) findViewById(R.id.textView6);
t1 = (TextView) findViewById(R.id.t1);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(view -> restartTimer());
restartTimer();
}
private void restartTimer() {
b1.setEnabled(false);
new CountDownTimer(45000, 1000) {
public void onTick(long millisUntilFinished) {
t1.setText("00:" + millisUntilFinished / 1000);
if (millisUntilFinished <= 10000) {
t1.setText("00:0" + millisUntilFinished / 1000);
}
}
public void onFinish() {
t1.setText("Tempo acabado");
b1.setEnabled(true);
}
}.start();
}

Related

how to implement Countdown timer with custom starting time?

I have been trying to implement a count down timer using handler in a simple text view. I need to set a custom time. for ex., the timer should start from
06:12:00.
-- This is the MainActivityenter code here code --.
public class MainActivity extends AppCompatActivity {
private Button startButton;
private Button pauseButton;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerValue = (TextView) findViewById(R.id.timerValue);
startButton = (Button) findViewById(R.id.startButton);
--listener for start button --
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
});
pauseButton = (Button) findViewById(R.id.pauseButton);
--listener for pause button--
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
});
}
private Runnable updateTimerThread = new Runnable() {
public void run()
{
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
int hours = mins/60;
secs = secs % 60;
timerValue.setText(String.format("%02d", hours)+":" +
(String.format("%02d", mins)) + ":"
+ String.format("%02d", secs) );
customHandler.postDelayed(this, 0);
}
};}
The output i am getting is here https://ibb.co/pd95Yww
public class MainActivity extends AppCompatActivity {
long timeInMilliseconds = 0L;
long timeSwapBuff = 22320000; // 6Hours:12Minutes:00Seconds
long updatedTime = 0L;
private Button startButton;
private Button pauseButton;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
String hms = String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(updatedTime),
TimeUnit.MILLISECONDS.toMinutes(updatedTime) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(updatedTime)),
TimeUnit.MILLISECONDS.toSeconds(updatedTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(updatedTime)));
timerValue.setText(hms);
customHandler.postDelayed(this, 0);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerValue = findViewById(R.id.timer);
startButton = findViewById(R.id.start);
pauseButton = findViewById(R.id.pause);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
});
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
});
}
}
I guess the issue is with pause button listener .....
It should be
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwapBuff = timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
});

How do I access my CountDownTimer to cancel it in Java?

Making a small game in Android Studio. Basically, the user will have a set amount of time to trigger a button press or the game will end. My CountDownTimer object is inside of a different function than my button click handler. How can I cancel the countDownTimer using cancel() from the button click handler.
Here is my code:
public countDownTimer timeLimit;
public void generate() {
final ProgressBar timer = (ProgressBar)findViewById(R.id.timer);`
int timeoutSeconds = 5000;
timer.setMax(timeoutSeconds);
timeLimit = new CountDownTimer(timeoutSeconds, 100) {
public void onTick(long millisUntilFinished) {
int timeUntilFinished = (int) millisUntilFinished;
timer.setProgress(timeUntilFinished);
}
public void onFinish() {
gameOver();
}
};
timeLimit.start();
}
public void buttonClicked(View v) {
timeLimit.cancel();
}
I'd be happy to hear any alternative ways to do this as well.
The code below works perfectly for me.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ProgressBar progressBar;
private CountDownTimer countDownTimer;
private Button stopTimerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
stopTimerButton = (Button)findViewById(R.id.button);
stopTimerButton.setOnClickListener(this);
int timeoutSeconds = 5000;
progressBar.setMax(timeoutSeconds);
countDownTimer = new CountDownTimer(timeoutSeconds,100) {
#Override
public void onTick(long millisUntilFinished) {
int timeUntilFinished = (int) millisUntilFinished;
progressBar.setProgress(timeUntilFinished);
}
#Override
public void onFinish() {
}
};
countDownTimer.start();
}
#Override
public void onClick(View view) {
if(view == stopTimerButton){
countDownTimer.cancel();
}
}
}

CountDown Timer App Android

I am creating a count down timer on the android platform.
I don't know how to store the remaining time on the timer (5 minutes on the timer) when the user presses the 'Stop' Button(PAUSE). So, if the user later presses the 'Start' Button again, it will continue counting down from where it left off. This is what i have done so far.
public class Timer_App extends Activity {
Button btn_Start, btn_Stop, btn_Reset;
TextView timer_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer_app);
//NEVER SLEEP!
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//Buttons
btn_Start = (Button) findViewById(R.id.Start);
btn_Stop = (Button) findViewById(R.id.Stop);
btn_Reset = (Button) findViewById(R.id.Reset);
//FONT
Typeface typeface = Typeface.createFromAsset(getAssets(), "Digital_Font.TTF");
timer_text = (TextView) findViewById(R.id.timer_view);
timer_text.setTypeface(typeface);
//Timer
timer_text.setText("05:00);
final CounterClass timer = new CounterClass(300000, 1000);
//Start btn
btn_Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer.start();
}
});
//Stop btn
btn_Stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer.cancel();
}
});
//Reset btn
btn_Reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
//TIMER CLASS
public class CounterClass extends CountDownTimer{
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
String hms = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
timer_text.setText(hms);
}
#Override
public void onFinish() {
}
}
}

Where do i add the timer code in my program ?

This is my top of my code:
public class MainActivity extends ActionBarActivity
{
private static final int MY_DATA_CHECK_CODE = 0;
public static MainActivity currentActivity;
TextToSpeech mTts;
private String targetURL;
private String urlParameters;
private Button btnClick;
private String clicking = "clicked";
private String[] ipaddresses = new String[]{
"http://10.0.0.1:8098/?cmd=nothing",
"http://192.168.1.10:8098/?cmd=nothing"};
private String iptouse = "";
private TextView text;
private boolean connectedtoipsuccess = false;
private int counter = 0;
private NotificationCompat.Builder mbuilder;
private Timer timer = new Timer();
TextView timerTextView;
long startTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
currentActivity = this;
initTTS();
}
And i want to add this code to my program so when i'm running my program i will the timer running.
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerTextView.setText(String.format("%d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_activity);
timerTextView = (TextView) findViewById(R.id.timerTextView);
Button b = (Button) findViewById(R.id.button);
b.setText("start");
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button b = (Button) v;
if (b.getText().equals("stop")) {
timerHandler.removeCallbacks(timerRunnable);
b.setText("start");
} else {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
b.setText("stop");
}
}
});
}
#Override
public void onPause() {
super.onPause();
timerHandler.removeCallbacks(timerRunnable);
Button b = (Button)findViewById(R.id.button);
b.setText("start");
}
What i want it to do is once i'm running the program the timer will start.
But i can't find how and where to add this part of the timer code.
I tried in the onCreate and i tried after the onCreate but it give errors since you can just add #override
You will probably want to set up another class (either in the same class or in its own class) and implement Runnable then from your on create make instance to that runnable.

TextView not Displaying Timer

For some reason whenever I try to update my TextView to show how many seconds a person has left. But for some reason now it isn't working.
public class MainActivity extends Activity {
private int index=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
final int[] Times= {6000,3000,7000,3000,4000,6000,3000};
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
final TextView textview =(TextView) findViewById(com.example.countdowntest.R.id.textView);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(index<Times.length){
CountDownTimer timer = new CountDownTimer(
Times[index], 0) {
public void onTick(long millisUntilFinished) {
textview.setText("seconds remaining: "+ millisUntilFinished / 1000);
}
public void onFinish() {
textview.setText("done!");
index++;
}
}.start();
}
}
});
}
}
It should display the updated seconds until it is finished because it is all within the onClick method which doesn't end until the timer reaches zero.
Your countDownInterval is 0
CountDownTimer(long millisInFuture, long countDownInterval)
What you have
new CountDownTimer(Times[index], 0) { // second param to the constructor is 0.
Should be
new CountDownTimer(30000, 1000) // whatever value you like
http://developer.android.com/reference/android/os/CountDownTimer.html
It won't update because you are passing 0 try passing 1000 which will update it at 1 second interval

Categories