i am trying to implement a countdown timer that starts from the number that the user inputs in the EditText. When i am running my program with the emulator, i realise that something goes wrong inside the countdown timer block since it does not enter inside this block.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText countDownTxt = (EditText) findViewById(R.id.editText2);
final EditText intervalTxt = (EditText) findViewById(R.id.editText1);
findViewById(R.id.button1).setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
int interval = Integer.parseInt(intervalTxt.getText().toString());
Log.d("buttonpressed", "interval countdown equals " + interval);
new CountDownTimer(Integer.parseInt(intervalTxt.getText().toString()), 1000) {
public void onTick(final long millisUntilFinished) {
Log.d("counttimer1", "enter");
runOnUiThread(new Runnable() {
#Override
public void run() {
countDownTxt.setText("" + millisUntilFinished / 1000);
}
});
countDownTxt.setText(""+ millisUntilFinished / 1000);
}
public void onFinish() {
countDownTxt.setText("done!");
}
}.start();
}
}
);
Any suggestions on solving this problemt ?
try using this
long timeVal = Long.parseLong(intervalTxt.getText().toString());
new CountDownTimer(timeVal, 1000) {
}
If you want the entered number by user present seconds, you should have like:
int time = Integer.parseInt(intervalTxt.getText().toString()) * 1000;
new CountDownTimer(time, 1000) {
...
Related
I want to build a 5 second timer that counts down to 0 in 1 second intervils and then resets to the initial value of 5 seconds. The timer needs to run continously. After looking at this thread,
Android - loop part of the code every 5 seconds
I used the CountDownTimer Class and called the start() method within the onFinish() method so that when the timer finished, it would reset to 5. It does run on a continous loop, however I notice that after the first loop, it either countsdown as 4-3-2-1-0 or 5-3-2-1-0.
Can somebody explain to me why this happens?
private long START_TIME_IN_MILLIS = 5000;
//set up our variables
private CountDownTimer timer;
private TextView textView;
private Button starttimer;
private long mTimeLeftInMillis = START_TIME_IN_MILLIS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view_countdown);
starttimer = findViewById(R.id.button_start_pause);
//set onclik listener when touch imput button
starttimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
beginTime();
}
});
}
//creating my own method
private void beginTime() {
timer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
start();
}
}.start();
}
private void updateCountDownText(){
int minutes= (int) (mTimeLeftInMillis / 1000)/ 60;
int seconds= (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
textView.setText(timeLeftFormatted);
}
}
Try this
#Override
public void onFinish() {
mTimeLeftInMillis = START_TIME_IN_MILLIS;
}
I want to display the timer in TextView in the format of like [ 19:59].so when i click the start button ,the timer will display like this for example,i want to set upto 20 mintues,it will display like [19:58][19:87].can anyone give some ideas or example code?
You can use the CountDownTimer.
http://developer.android.com/reference/android/os/CountDownTimer.html
TextView _tv = (TextView) findViewById( R.id.textView1 );
new CountDownTimer(20*60000, 1000) {
public void onTick(long millisUntilFinished) {
_tv.setText("seconds remaining: " +new SimpleDateFormat("mm:ss:SS").format(new Date( millisUntilFinished)));
}
public void onFinish() {
_tv.setText("done!");
}
}.start();
To cancel just call cancel on the timer.
public final void cancel()
Cancel the countdown.
package com.example.testproject;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity {
public int seconds = 60;
public int minutes = 10;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView tv = (TextView) findViewById(R.id.main_timer_text);
tv.setText(String.valueOf(minutes)+":"+String.valueOf(seconds));
seconds -= 1;
if(seconds == 0)
{
tv.setText(String.valueOf(minutes)+":"+String.valueOf(seconds));
seconds=60;
minutes=minutes-1;
}
}
});
}
}, 0, 1000);
}
}
//start button click
CountDown timer = new CountDown(180000, 1000);
timer.start();
//stop button click
timer.stop();
//countdown class
public class CountDown extends CountDownTimer {
public CountDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
long ms = millisUntilFinished;
String text = String.format("%02d\' %02d\"",
TimeUnit.MILLISECONDS.toMinutes(ms) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(ms)),
TimeUnit.MILLISECONDS.toSeconds(ms) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(ms)));
textViewTimer.setText(text);
}
#Override
public void onFinish() {
textViewTimer.setText("ffinish");
}
}
do it this way activity_timer.xml
<android.support.v7.widget.LinearLayoutCompat
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Chronometer
android:id="#+id/chronometer2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.v7.widget.LinearLayoutCompat>
And in Activity
public class TimerActivity extends AppCompatActivity {
private Chronometer chronometer2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
chronometer2 = findViewById(R.id.chronometer2);
chronometer2.start();
}
}
You can also use stop
chronometer2.stop();
Re Start
chronometer2.setBase(SystemClock.elapsedRealtime());
chronometer2.start();
Here I have use Timer class to display timer
public class FourthActivity extends AppCompatActivity {
Button startButton, pauseButton;
TextView timerValue;
Timer timer;
int seconds = 0, minutes = 0, hour = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fourth);
bindView();
timer = new Timer();
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (seconds == 60) {
timerValue.setText(String.format("%02d", hour) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
minutes = seconds / 60;
seconds = seconds % 60;
hour = minutes / 60;
}
seconds += 1;
timerValue.setText(String.format("%02d", hour) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
}
});
}
}, 0, 1000);
}
});
}
private void bindView() {
timerValue = (TextView) findViewById(R.id.timerValue);
startButton = (Button) findViewById(R.id.startButton);
}
}
In layout, there are one TextView and one Button to start timer. I have use Timer class method scheduleAtFixedRate. Time will be displayed in hh:mm:ss form.
This can be done using cronometer, the most main reason is supporting API 1+, which is quite impressive rather than TextClock, which supports API 17+.
You can do lots of other things with cronometer. for example you can set start time in it
chronometer.setBase(SystemClock.elapsedRealtime());
You can also learn about it more here.
I made code for timer display in textView.The formate is for e.g:- 02:59:00
You can follow this link to get the Step By Step Code.
https://stackoverflow.com/a/58316149/11613683
Hey i recently got into android and made my first app which was meant to start a run down timer of 60 seconds when the user pressed start button. The application sets the content view fine and displays 60 but when i click the start button it displays 59 successfully and then the app crashes.Here's the code(it has only one activity)
public class test1activity extends Activity
{
Thread countdown;
long f, pa, jee;
TextView ytvp;
String s;
TextView uyti;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ytvp = (TextView) findViewById(R.id.textView2);
uyti = (TextView) findViewById(R.id.tv2);
countdown = new Thread() {
public void run() {
jee = (System.currentTimeMillis()) / 1000;
while ((((System.currentTimeMillis()) / 1000) - jee) < 60)
{
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
f = ((System.currentTimeMillis()) / 1000) - jee;
pa = 60 - f;
s = String.valueOf(pa);
ytvp.setText(s);
}
}
}
};
}
public void whenclickstart(View view) {
countdown.start();
}
You cannot set UI elements from inside another thread(Non UI thread). So you cannot use this below line.
ytvp.setText(s);
Try something like this, you dont need threading for what you are trying to do
new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
ytvp.setText("" + millisUntilFinished/1000);
}
public void onFinish() {
ytvp.setText(""+0);
}
}.start();
If you do not want to use countdowntimer replace setText with
runOnUiThread(new Runnable() {
public void run() {
ytvp.setText(s);
}
});
I want to do countdown timer with pause and restart.Now i am displaying countdown timer By implenting ontick() and onfinish().please help me out.HEre is th code for countdown timer
final CountDownTimer Counter1 = new CountDownTimer(timervalue1 , 1000)
{
public void onTick(long millisUntilFinished)
{
System.out.println("onTick method!"(String.valueOf(millisUntilFinished/1000)));long s1=millisUntilFinished;
}
public void onFinish()
{
System.out.println("Finished!");
}
}
in onTick method..save the milliseconds left
long s1=millisUntilFinished;
when you want to pause the timer use..
Counter.cancel();
when you want to resume create a new countdowntimer with left milliseconds..
timervalue=s1
counter= new Counter1();
counter.start();
See this link
I would add something to the onTick handler to save the progress of the timer in your class (number of milliseconds left).
In the onPause() method for the activity call cancel() on the timer.
In the onResume() method for the activity create a new timer with the saved number of milliseconds left.
Refer the below links
LINK
LINK
My first answer on stackOverFlow, hope it should help :) ...
This is how I solved the problem, control timer from Fragment, Bottomsheet, Service, Dialog as per your requirement, keep a static boolean variable to control.
declare in your Activity:
long presetTime, runningTime;
Handler mHandler =new Handler();
Runnable countDownRunnable;
Toast toastObj;
public static boolean shouldTimerRun = true;
TextView counterTv;
In onCreate:
presetTime =60000L;
runningTime= presetTime;
//setting up Timer
countDownRunnable=new Runnable() {
#Override
public void run() {
if (shouldTimerRun) //if false, it runs but skips counting
{
counterTv.setText(simplifyTimeInMillis(runningTime));
if (runningTime==0) {
deployToast("Task Completed"); //show toast on task completion
}
runningTime -= 1000;
presetTime = runningTime; //to resume the timer from last position
}
mHandler.postDelayed(countDownRunnable,1000); //simulating on-tick
}
};
mHandler.post(countDownRunnable); // Start our CountdownTimer
Now, whenever you want to pause the timer change the value of shouldTimerRun false and to resume make it true.
#Override
public void onResume() {
super.onResume();
shouldTimerRun=true;
}
#Override
public void onPause() {
super.onPause();
shouldTimerRun=false;
deployToast("Timer is paused !!");
}
Helping methods: (can be skipped)
public static String simplifyTimeInMillis(long time) {
String result="";
long difference = time;
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
if (difference<1000){
return "0";
}
if (difference>=3600000) {
result = result + String.valueOf(difference / hoursInMilli) + "hr ";
difference = difference % hoursInMilli;
}
if (difference>=60000) {
result = result + String.valueOf(difference / minutesInMilli) + "m ";
difference = difference % minutesInMilli;
}
if (difference>=1000){
result = result + String.valueOf(difference / secondsInMilli) + "s";
}
return result;
}
public void deployToast(String msg){
if (toastObj!=null)
toastObj.cancel();
toastObj = Toast.makeText(mContext,msg,Toast.LENGTH_SHORT);
toastObj.show();
}
I'm using two private vars in this case:
private long startPauseTime;
private long pauseTime = 0L;
public void pause() {
startPauseTime = System.currentTimeMillis();
}
public void resumen(){
pauseTime += System.currentTimeMillis() - startPauseTime;
}
I am afraid that it is not possible to pause or stop CountDownTimer and pausing or stopping in onTick has no effect whatsoever user TimerTask instead.
Set up the TimerTask
class UpdateTimeTask extends TimerTask {
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timeLabel.setText(String.format("%d:%02d", minutes, seconds));
}
}
if(startTime == 0L) {
startTime = evt.getWhen();
timer = new Timer();
timer.schedule(new UpdateTimeTask(), 100, 200);
}
You can add event listener's like this..
private Handler mHandler = new Handler();
...
OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
if (mStartTime == 0L) {
mStartTime = System.currentTimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
}
};
OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
mHandler.removeCallbacks(mUpdateTimeTask);
}
};
For more refer to Android Documentation.
//This timer will show min:sec format and can be paused and resumed
public class YourClass extends Activity{
TextView timer;
CountDownTimer ct;
long c = 150000; // 2min:30sec Timer
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.YourXmlLayout);
timer = (TextView)findViewById(R.id.Yourtimer)
startTimer(); // it will start the timer
}
public void startTimer(){
ct = new CountDownTimer(c,1000) {
#Override
public void onTick(long millisUntilFinished) {
// Code to show the timer in min:sec form
// Here timer is a TextView so
timer.setText(""+String.format("%02d:%02d",millisUntilFinished/60000,(millisUntilFinished/1000)%60));
c = millisUntilFinished; // it will store millisLeft
}
#Override
public void onFinish() {
//your code here
}
};
ct.start();
}
/*===========================================================
*after creating this you can pause this by typing ct.cancel()
*and resume by typing startTimer()*/
public class MainActivity extends AppCompatActivity {
TextView textView;
CountDownTimer ctimer;
boolean runCountDown;
private long leftTime;
private static final long MILL_IN_FUTURE = 6000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view);
textView.setText("Click to start");
textView.setOnClickListener(this::clickStartAndPauseAndResume);
leftTime = MILL_IN_FUTURE;
}
public void clickStartAndPauseAndResume(View view) {
if (!runCountDown) {
long time = (leftTime == 0 || leftTime == MILL_IN_FUTURE) ? MILL_IN_FUTURE : leftTime;
ctimer = new CountDownTimer(time, 1) {
#Override
public void onTick(long l) {
leftTime = l;
textView.setText(l + "ms");
}
#Override
public void onFinish() {
textView.setText("Done");
leftTime = 0;
runCountDown = false;
textView.postDelayed(new Runnable() {
#Override
public void run() {
textView.setText("Click to start");
}
}, 1000);
}
}.start();
runCountDown = true;
} else {
ctimer.cancel();
textView.setText(textView.getText() + "\n Click to resume");
runCountDown = false;
}
}
}
A nice and simple way to create a Pause/Resume for your CountDownTimer is to create a separate method for your timer start, pause and resume as follows:
public void timerStart(long timeLengthMilli) {
timer = new CountDownTimer(timeLengthMilli, 1000) {
#Override
public void onTick(long milliTillFinish) {
milliLeft=milliTillFinish;
min = (milliTillFinish/(1000*60));
sec = ((milliTillFinish/1000)-min*60);
clock.setText(Long.toString(min)+":"+Long.toString(sec));
Log.i("Tick", "Tock");
}
The timerStart has a long parameter as it will be reused by the resume() method below. Remember to store your milliTillFinished (above as milliLeft) so that you may send it through in your resume() method. Pause and resume methods below respectively:
public void timerPause() {
timer.cancel();
}
private void timerResume() {
Log.i("min", Long.toString(min));
Log.i("Sec", Long.toString(sec));
timerStart(milliLeft);
}
Here is the code for the button FYI:
startPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(startPause.getText().equals("Start")){
Log.i("Started", startPause.getText().toString());
startPause.setText("Pause");
timerStart(15*1000);
} else if (startPause.getText().equals("Pause")){
Log.i("Paused", startPause.getText().toString());
startPause.setText("Resume");
timerPause();
} else if (startPause.getText().equals("Resume")){
startPause.setText("Pause");
timerResume();
}
I'm attempting to do a guessing game, of sorts. The issue is my timer bleeds into the next one after a question is answered (button pressed) and a new timer starts. This leads to two timers changing a textview at different intervals, which is not how it's supposed to be. I'd like to know how to stop my previous countdown and start a new one. Thanks! Here's my code:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final TextView textic = (TextView) findViewById(R.id.button1);
long total = 30000;
final CountDownTimer Count = new CountDownTimer(total, 1000) {
public void onTick(long millisUntilFinished) {
textic.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
textic.setText("OUT OF TIME!");
finish();
}
};
Count.start();
Heven't tested the code but I would use something like this:
final TextView textic = (TextView) findViewById(R.id.button1);
final android.os.CountDownTimer Count = new android.os.CountDownTimer(total, 1000) {
public void onTick(long millisUntilFinished) {
textic.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
textic.setText("OUT OF TIME!");
}
};
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Count.cancel();
Count.start();
}
});
finish CountDownTimer in On finish
#Override
public void onFinish() {
Log.v(TAG, "On Finish");
textvieew.setText("your text");
countDownTimer.cancel();
}