countdown timer in text view - android

i wrote this code and i want when i click on btnGetPincode, a 60 sec count down timer start to run.
but it didnt happen and the result in textview= 00:00 and nothing happen. why?
this is my code:
btnGetPinCode.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btnGetPinCode.setClickable(false);
btnGetPinCode.setBackgroundResource((R.drawable.button4));
txtShowPinCode.setVisibility(View.VISIBLE);
//initialize timer duration
long duration = TimeUnit.MINUTES.toMillis(1);
//initialize timer countdown timer
new CountDownTimer(duration, 1000) {
#Override
public void onTick(long millisUntilFinished) {
String duration2 = String.format(Locale.ENGLISH, "%02d : %02d"
, TimeUnit.MILLISECONDS.toMinutes(1)
, TimeUnit.MILLISECONDS.toSeconds(1) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(1)));
//set converted time to textView
txtTimer.setVisibility(View.VISIBLE);
txtTimer.setText(duration2+"");
btnOk.setText(duration2);
}
#Override
public void onFinish() {
//when timer finished, hide text view
txtTimer.setVisibility(View.INVISIBLE);
btnGetPinCode.setBackgroundResource(R.drawable.button);
btnGetPinCode.setClickable(true);
}
}.start();
});
}

Issue: You set 1 in each argument in duration2 variable, so the TextView won't ever be changed, you need to set the actual value that is changed on every timer tick which is the parameter of the onTick() method >> millisUntilFinished
Change your timer to:
new CountDownTimer(duration, 1000) {
#Override
public void onTick(long millisUntilFinished) {
String duration2 = String.format(Locale.ENGLISH, "%02d : %02d"
, TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) //<<<<< change here
, TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - //<<<< change here
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))); //<<<<< change here
//set converted time to textView
txtTimer.setVisibility(View.VISIBLE);
txtTimer.setText(duration2+"");
btnOk.setText(duration2);
}
#Override
public void onFinish() {
//when timer finished, hide text view
txtTimer.setVisibility(View.INVISIBLE);
btnGetPinCode.setBackgroundResource(R.drawable.button);
btnGetPinCode.setClickable(true);
}
}.start();

The main problem lies in calculation of time duration2
//Declare timer
CountDownTimer cTimer = null;
cTimer = new CountDownTimer(duration, 1000) {
#Override
public void onTick(long millisUntilFinished) {
String duration2 = String.format(Locale.ENGLISH, "%02d : %02d"
, TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) //Here is the problem
, TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - //Here is the problem
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))); //<<<<< change here
//set converted time to textView
txtTimer.setVisibility(View.VISIBLE);
txtTimer.setText(duration2+"");
btnOk.setText(duration2);
}
#Override
public void onFinish() {
//when timer finished, hide text view
txtTimer.setVisibility(View.INVISIBLE);
btnGetPinCode.setBackgroundResource(R.drawable.button);
btnGetPinCode.setClickable(true);
}
}.start();
You should also need to clean up the references so as to prevent memory leaks. This needs to be called cTtimer.cancel() whenever the onDestroy()/onDestroyView() in the owning Activity/Fragment is called.
void cancelTimer() {
if(cTimer!=null)
cTimer.cancel();
}

Related

countDowntimer not Resetting for a new Value and shows the old value always

I am trying to show a countDownTimer in my activity. the value I am using in the countDowntimer is coming from a recyclerview of another activity using bundle. when I click one of the recyclerview time for the first time, the countDownTimer shows the time running perfectly. but when I select another time, the old instance continues to run. I have implemented the cancel and onFinish() methods to but they are not working as I want. I searched everywhere but everyone suggested about cancel and onFinish() methods. I am unable to find a solution now.
public void getData() {
if(countDownTimer!=null){
countDownTimer.cancel();
}
if (replaceTime != null) {
time = Integer.parseInt(replaceTime);
} else
Toast.makeText(FullTimerActivity.this, "",
Toast.LENGTH_LONG).show();
totalTimeCountInMilliseconds = time;
timeBlinkInMilliseconds = 30 * 1000;
countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
#Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
if (leftTimeInMilliseconds < timeBlinkInMilliseconds) {
if (blink) {
// mTextField.setVisibility(View.VISIBLE);
// if blink is true, textview will be visible
} else {
// mTextField.setVisibility(View.INVISIBLE);
}
blink = !blink;
}
String a = String.format("%02d", seconds / 60) + ":" + String.format("%02d", seconds % 60);
textView.setText(a);
}
#Override
public void onFinish() {
Toast.makeText(FullTimerActivity.this, "Finished", Toast.LENGTH_SHORT).show();
}
}.start();
}
thank you in advance.
In onFinish() also set the text to TextView like below
textView.setText("0");

Why does timer loop not initialize at initial value when it calls onFinish() method?

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;
}

Spinner is closed upon setting some text in CountDownTimer

I am trying to show a timer on the screen and on that screen I have a TextView and a RecyclerView.
The RecyclerView contains some Spinners.
When the onTick() method is executed, the Spinners are closed automatically.
Please provide any solution to this problem.
Code of my CountDownTimer
public class CountDownTimerClass extends CountDownTimer {
public CountDownTimerClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
String time = String.format(Locale.US, "%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
mTvTimer.setText(time);
}
#Override
public void onFinish() {
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member_enter_details);
mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);
mTvTimer = (TextView) findViewById(R.id.tv_timer);
mTvBlockNo = (TextView) findViewById(R.id.tv_block_no);
mRlHeader = findViewById(R.id.rlHeader);
//hit for web service. In the response i am starting timer
getData(Event.GET_EXPIRATION_TIME);
}
Pretty sure it's closing because you're calling setText on another view. That may trigger a focus change which would cause the Spinner to close.
You may be able to avoid this by setting focusable to false on the TextView (via XML preferably), or calling clearFocus() on the TextView after setText()
You should update your label or textview's text in the UI Thread, so your code should look like
public void onTick(long millisUntilFinished) {
String time = String.format(Locale.US, "%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
runOnUiThread(new Runnable() {
#Override
public void run() {
mTvTimer.setText(time);
}
});
}

Android - CountDownTimer will not use a variable as the first parameter

I'm trying to pass the countdowntimer a variable and use that variable as the amount of milliseconds to count down. If I simply enter the value the countdown works properly, but if I pass it a long variable it just runs the onFinish function.
Here's the actual code:
public CountDownTimer countDown = new CountDownTimer(respawnTime, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timer =(Integer)(int) millisUntilFinished / 1000;
if(timer < 31)
timerText.setTextColor(Color.parseColor("#FF0000"));
timerText.setText(timer.toString());
}
#Override
public void onFinish() {
timerText.setTextColor(Color.parseColor("#00FF00"));
timerText.setText("UP");
}
};
At this point I have respawnTime set to equal 360000 hoping for a 360 second countdown, but like I said it just immediately runs the onFinish. Simply changing the first parameter to a literal instead of a variable fixes everything but I need to use a variable here. Thanks in advance for the help!
Change
#Override
public void onTick(long millisUntilFinished) {
to
#Override
public void onTick(long respawnTime) {
use the variable you are sending in the constructor in onTick().
Edit
Here is one of mine
private class MyCountDown extends CountDownTimer
{
long duration, interval;
public MyCountDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
duration = millisInFuture;
interval = countDownInterval;
start();
}
#Override
public void onFinish() {
secs = 10;
Intent intent = new Intent(CalibrationTimeoutScreen.this, CalibrationTakeTempScreen.class);
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivity(intent);
CalibrationTimeoutScreen.this.finish();
}
#Override
public void onTick(long duration) {
cd.setText(String.valueOf(secs));
secs = secs - 1;
}
}
You did not run start(). Simply add .start() after the last '}' or add a new line calling countDown.start().

Android countdown timer wont accept variable

i just started to learn creating android apps. I wanted to create a simple count down timer that takes a value from a edittext but countdown timer does not seem to run.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countDownTxt = (TextView) findViewById(R.id.countDownView);
intervalTxt = (TextView) findViewById(R.id.intervalText);
findViewById(R.id.startBN).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
int testInt = 30;
//countDownTxt.setText(intervalTxt.getText());
int interval = Integer.parseInt(intervalTxt.getText().toString());
Log.d("buttonpressed", "interval for countdown is " + interval);
cdt = new CountDownTimer(Integer.parseInt(intervalTxt.getText().toString()), 1000) {
public void onTick(long millisUntilFinished) {
Log.d("counttimer1", "haha1");
countDownTxt.setText(""+ millisUntilFinished / 1000);
}
public void onFinish() {
cancel();
}
}.start();
}
}
);
}
In particular, this program works only if i enter a numerical value such as 30000 in the 1st parameter of the CountDownTimer "cdt = new CountDownTimer(testInt, 1000)"
Can someone enlighten me please? Thank you!
"Doesn't work" how? You should post the error message you're getting or other symptoms of "doesn't work."
What's probably happening is CountDownTimer accepts only long values as the first parameter of its constructor. Not int values.
Change int testInt = 30 to long testLong = 10000.0f and see what happens.
The first parameter means milliseconds, by the way, so "30" isn't really going to get you much in the first place.
onTick() method is called in a separate Thread. But you don't have right to use setText() method outside the GUI Thread.
You must use a Handler object or Activity.postOnUiThread() method to execute something in the GUI Thread :
cdt = new CountDownTimer(Integer.parseInt(intervalTxt.getText().toString()), 1000) {
public void onTick(long millisUntilFinished) {
Log.d("counttimer1", "haha1");
runOnUiThread(new Runnable() {
#Override
public void run() {
countDownTxt.setText("" + millisUntilFinished / 1000);
}
});
countDownTxt.setText(""+ millisUntilFinished / 1000);
}
public void onFinish() {
cancel();
}
}.start();
For more informations, read http://developer.android.com/guide/components/processes-and-threads.html#Threads

Categories

Resources