I am trying to use this timer...when I call countDownTimer.start()
I can see in the debugger that the timeleft variable get updated to the value=120000 that I want but the timer doesn't execute the onTick method. It jumps straight to onFinish. But if I give timeLeft a literal it works.
volatile long timeLeft=0;
CountDownTimer countDownTimer=new CountDownTimer( timeLeft,1000) {
#Override
public void onTick(long timeLeft) {
TextView timeView= (TextView)findViewById(R.id.timer);
long longTime=(timeLeft / 1000);
Integer intTime=(int)longTime;// convert long to int
timeView.setText(String.valueOf(intTime));}
#Override
public void onFinish() {correctDialog("Sorry,Time Is Up!!");}};}
(timeLeft is not fixed)
Here the first parameter in the CountDownTimer() constructor is the millisInFuture . You are giving this value as 0. So it will finish whenever you start the timer. Give its value how much time you want to execute the times like 10000 or 20000 etc...
So initialize timeleft
volatile long timeLeft=10000;
Check the documentation CountDownTimer
try like this:
public class MainActivity extends Activity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
CountDownTimer timer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000);
tv.setText("seconds remaining: " + String.valueOf(seconds));
}
public void onFinish() {
tv.setText("Finished!!");
}
}.start();
}
}
Xml:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
I think it's solve your problem.
You set the timeLeft = 0;this means that the timer would run for 0 milliseconds. the timeLeft should equal to the amount of milliseconds you want the timer to run for. So, for a thirty second timer, volatile long timeLeft = 30000;
Hope this helps
Precise Answer to the question is, you forgot to start the timer.
i.e. you missed countDownTimer.start();
Code for CountDownTimer:
int tickTime = 1000; //For every second
int finishTime = 30000; //Complete of countdowntimer
TextView yourTextView;
new CountDownTimer(tickTime, finishTime){
#Override
public void onTick(long l) {
Log.i("CountDownTimer", "onTick");
yourTextView.setText(String.valueOf(l));
}
#Override
public void onFinish() {
Log.i("CountDownTimer", "onFinish");
}
}.start();
This countdowntimer comes on every second in onTick() method and after 30 seconds it will come in onFinish() method.
Done
Related
I have to show countdown in my app,
i getting two timestamp
1. startTime
2. endTime
please help to show countdown timer.
Thank you
You can use CountdownTimer like this. It uses milliseconds, for example this uses 1 second interval(1000 milliseconds) as it counts down.
int input = Integer.valueOf(String.valueOf(mCount_Entry.getText())) * 1000;
CountDownTimer countDownTimer = new CountDownTimer(input, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mDisplay.setText("seconds remaining: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
mDisplay.setText("Countdown is over, boom*****");
}
}.start();
I want to use a Countdown Timer but have a problem. If i start it and then press a Back button (change lifecycle to onStop) and return back to activity - i cant see timer values in TextView. But in Logcat i see that the timer works.
Question: how to update TextView after return on activity (onResume)
UPDATE.
While i'll not close activity this code works as it should - well. But if i press back button there is no values in TextView.
The timer method code (this method is called from onCreate):
timer = new CountDownTimer(rest + 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
secondsUntilFinish = Math.round(millisUntilFinished / 1000);
String minutes = String.format("%02d",TimeUnit.SECONDS.toMinutes(secondsUntilFinish));
String seconds = String.format("%02d",TimeUnit.SECONDS.toSeconds(secondsUntilFinish) - TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(secondsUntilFinish)));
tvRoutineTimer.setText(getResources().getString(R.string.exercise_rest_timer, minutes, seconds));
Log.d(LOG_TAG, "onTick = " + getResources().getString(R.string.exercise_rest_timer, minutes, seconds));
}
#Override
public void onFinish() {
tvRoutineProgress.setText(getString(R.string.routine_progress, currentStep, totalSteps));
tvRoutineTimer.setText(getString(R.string.exercise_rest_timer, "00", "00"));
notificationAfterRest();
btnExerciseDone.setText(getString(R.string.button_exercise_done));
btnExerciseDone.setEnabled(true);
tvExercisePlaceholder.setText(getString(R.string.exercise_current_title));
}
}.start();
You need to update your TextView from the UI thread. Update your TextView like this:
runOnUiThread(new Runnable() {
#Override
public void run() {
tvRoutineTimer.setText(getResources().getString(R.string.exercise_rest_timer, minutes, seconds));
});
Place the runOnUiThread inside the onTick()
I have defined a chronometer;
protected Chronometer chrono;
protected int baseTime;
protected int stopTime;
protected long elapsedTime;
My program asks questions to the user and i want to set a timer based on the user's input. I want a timer which starts at 10 to 0. How can i do that?
Also, I want to show the remaining time on the screen.
Use CountDownTImer instead,
new CountDownTimer(10000, 1000) { //Sets 10 second remaining
public void onTick(long millisUntilFinished) {
mTextView.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextView.setText("done!");
}
}.start();
Note : It's not possible to start Chronometer reversely because the Chronometer widget only counts up.
Edit: From API level 24, it is possible to perform count down using chronometer via help of Chronometer#setCountDown(true) method.
So i have here Quiz App and have timer. So what i want to happen for example i have set the timer for 15 seconds and if the user answer the question in 5 seconds i want the 10 seconds ramaining become 10 points and it will add to previous score plus the score of you will get upon answering the questions. so for now i have this ...
if(savedInstanceState!=null){
//saved instance state data
int exScore = savedInstanceState.getInt("score");
scoreText.setText("Score: "+exScore);
}
Timer = new CountDownTimer(15000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
tv_time.setText("" + millisUntilFinished / 1000);
int progress = (int) (millisUntilFinished / 150);
progressBar.setProgress(progress);
}
#Override
public void onFinish() {
progressBar.setProgress(0);
timeUp(context);
}
}.start();
and here is the one for onclick. if the user answer correctly it will add 10points automatically
public void onClick(View view) {
Button clicked = (Button) view;
int exScore = getScore();
if (clicked.getText().toString().equals(this.active_question.getAnswer()) ) {
if (this.questions.size() > 0) {
setQuestion(questions.poll());
scoreText.setText("Score: " + (exScore + 10))
} else {
CustomGameOver cdd = new CustomGameOver(PlayQuizActivity.this);
cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
cdd.show();
setHighScore();
Timer.cancel();
}
}
I dont have any idea on how to get the remaianing time on CountdownTimer and add it as a score when the answer is correct. could anyone please help me please.
Just use millisUntilFinished from onTick of the CountDownTimer
And the bonus will be millisUntilFinished/1000
P.S I think you better use a lower interval than 1000, so the ProgressBar will seem smoother.
All you need to do is declare a long variable timeleft in your MainActivity.
long timeleft;
Then, when you create a new Timer, set the "onTick" override to update the timeleft variable each "onTick" (which in the following example is 1000 milliseconds )
timer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long millisecondsUntilFinished) {
timeleft = millisecondsUntilFinished;
}
}
Your app can access then the variable timeleft every time you need to check how much time is left.
score = score + timeleft / 1000; // divide by 1000 to get seconds
Have in mind that if you need to update the timer, you have to cancel it and create a new timer with the updated time left (and the same override);
timeleft = timeleft + bonustime; // (if you want to add bonus time, remember has to be in milliseconds)
if( timer != null){ timer.cancel();} // better check first if the timer exists
timer = new CountDownTimer(timeleft, 1000) {
#Override
public void onTick(long millisecondsUntilFinished) {
timeleft = millisecondsUntilFinished;
}
I have an edit text for entering a time in minutes, a button to start a countdown timer using the minutes entered in the edit text which updates a text view, and a button which I want to cancel the countdown timer before it finishes.
The problems I'm having are...the variable the countdown timer needs (the milliseconds) can't get assigned until I click the start timer button because it's coming from an edit text. So I created the countdown timer inside of the onClick for the start timer button. However...I want another button to cancel the timer...and it doesn't have access to the countdown timer. So that didn't solve anything and I'm confused at how to do this. Any advice would help.
Edit: I just realized I could move the stop timer button with the listener to the start timer button onClick also...under the countdown timer. I'm just confused about how the countdown timer could find the milliseconds variable if I have countdown timer outside of the start timer onClick. I guess moving the stop timer under countdown timer works...but still feels like I'm missing something.
Edit2: I tried moving countDownTimer into onCreate and making milliseconds global...but I have to make countDownTimer final in order for the buttons to be able to use it, and countDownTimer just skips to onFinish.
mTimerTextView = (TextView)findViewById(R.id.timer_text_view);
mTimerEditText = (EditText)findViewById(R.id.timer_edit_text);
mStartTimerButton = (Button)findViewById(R.id.btn_start_timer);
mStartTimerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Getting time in minutes from edit text
int timeEntered = Integer.parseInt(mTimerEditText.getText().toString());
long milliseconds = timeEntered * 60000;
CountDownTimer countDownTimer = new CountDownTimer(milliseconds, 1000) {
#Override
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000) % 60;
int minutes = (int) ((millisUntilFinished / (1000*60)) % 60);
int hours = (int) ((millisUntilFinished / (1000*60*60)) % 24);
mTimerTextView.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds));
}
#Override
public void onFinish() {
new AlertDialog.Builder(DailyGoalActivity.this)
.setTitle("Time's Up")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
}
};
countDownTimer.start();
}
});
mStopTimerButton = (Button)findViewById(R.id.btn_stop_timer);
mStopTimerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// countDownTimer.cancel(); <- How could I do this?
}
});
there are two possible reason for your problem first one is that you need to create countdown timer in onCreate and second one is that you are stopping null countdown timer.
solution-1 you can use a boolean variable to check that timer has start or not and then start timer accordingly on button click.Apart from this initialize timer in on create and start in on click follow this code please follow this link
solution-2 to stop the timer use this code
if(countDownTimer != null) {
countDownTimer .cancel();
countDownTimer = null;
}
Isn't the simple solution to declare CountDownTimer variable globally?
Move this code to onCreate
CountDownTimer countDownTimer = new CountDownTimer(milliseconds, 1000) {
#Override
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000) % 60;
int minutes = (int) ((millisUntilFinished / (1000*60)) % 60);
int hours = (int) ((millisUntilFinished / (1000*60*60)) % 24);
mTimerTextView.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds));
}
}
Then start timer in Start button's onClick and cancel in Stop button's onClick.
Hope it helps.