I wanted to program a timer that can be set up by clicking a button. For example button one sets a timer to 1 minute. Button 2 sets the timer to 2 minutes. the third button should start and stop the timer. I tried many code samples but it is not running. Has someone an idea how to solve this?
public void mittelBtn (View view){
EditText timerText = (EditText) findViewById(R.id.timerText);
timerText.setText("7:00");
countDownTimer =new CountDownTimer(420000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
}
}.start();
}
public void weichPlusBtn (View view){
EditText timerText = (EditText) findViewById(R.id.timerText);
timerText.setText("5:00");
countDownTimer =new CountDownTimer(300000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
}
}.start();
Because in onTick you should do something.
public void weichPlusBtn (View view){
EditText timerText = (EditText) findViewById(R.id.timerText);
timerText.setText("5:00");
//Set a couter variable
int counter = 5 * 60;
countDownTimer =new CountDownTimer(300000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
counter--;
String newTime = secondsToString(counter);
timerText.setText(newTime);
}
#Override
public void onFinish() {
}
}.start();
private String secondsToString(int pTime) {
return String.format("%02d:%02d", pTime / 60, pTime % 60);
}
Hope this helps. Good luck.
Related
I'm Making a countdown timer app but the problem when the countdown finish it doesn't show me 00:00
I'm using seek bar the set the timer when I use 100 in countDown interval it works but I want it to be 1000 in the interval and I'm following a tutorial I write the same code shown in the tutorial it works for him and not for me please help me guys
public void buttonClicked(View view)
{
CountDownTimer countDown = new CountDownTimer(timerSeek.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timerUpdate((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
Toast.makeText(MainActivity.this, "finish", Toast.LENGTH_SHORT).show();
}
}.start();
}
/* ========================================================= */
/* ========================================================= */
public void timerUpdate(int secondsLeft)
{
int minutes = secondsLeft / 60;
int seconds = secondsLeft - (minutes * 60);
String secondsStr = Integer.toString(seconds);
if (seconds <= 9)
secondsStr = "0" + secondsStr;
timerText.setText(Integer.toString(minutes) + " : " + secondsStr);
}
/* ============================================================ */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerSeek = (SeekBar) findViewById(R.id.timerSeek);
timerText = (TextView) findViewById(R.id.timerText);
timerSeek.setMax(600);
timerSeek.setProgress(30);
timerSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
timerUpdate(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
This is because onTick() method is not called when the countdown is finished. Rather, onFinish() is called. An easy solution that appears to me is that you can explicitly show 00:00 inside onFinish(), since this method is called when the countdown is finished.
I need your help to get a variable from the countdown and set that value to text view. Suppose if countdown stopped at 0:40 sec and I want to put that number to text view.
So I'm using Seekbar to update the time with progress and a textview. And suppose I stopped at a certain number, next time I start again, let the number start from when it stopped. I have uploaded the image of output. Thanks
I learned to create this app from udemy online tutorial. Its called Complete android developer course- Build 23 Apps!!. Its lesson 38- App Egg timer.
This is my MainActivity.java file
public class MainActivity extends AppCompatActivity {
TextView timerTv;
SeekBar timerSeekBar;
Button startBtn;
CountDownTimer countDownTimer;
boolean counterisActive = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerTv = (TextView) findViewById(R.id.countdowntimertextview);
timerSeekBar = (SeekBar) findViewById(R.id.timerSeekBar);
startBtn = (Button) findViewById(R.id.startBtn);
timerSeekBar.setMax(300);
timerSeekBar.setProgress(20);
timerSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
updateTimer(progress);
Log.i("Seekbar changes", String.valueOf(progress), null);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
public void resetTimer(){
//This is where I want to set the text.
timerTv.setText("Trying to get text from countdown!!");
startBtn.setText("START!");
timerSeekBar.setEnabled(true);
countDownTimer.cancel();
timerSeekBar.setProgress(20);
counterisActive = false;
}
public void buttonClicked(View view){
if(counterisActive){
resetTimer();
}else {
counterisActive = true;
timerSeekBar.setEnabled(false);
startBtn.setText("STOP!");
Log.i("Button Clicked", "Clicked");
countDownTimer = new CountDownTimer(timerSeekBar.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.templebell);
mediaPlayer.start();
Log.i("Timer Finished", "Done!!");
resetTimer();
}
}.start();
}
}
public void updateTimer(int secondLefts){
int minutes = secondLefts / 60;
int seconds = secondLefts - (minutes * 60);
String secondString = Integer.toString(seconds);
if(seconds <= 9) {
secondString = "0" + seconds;
}
timerTv.setText(minutes + " : " + secondString );
}
}
I think you need to pause the timer.
First create a global long variable in your activity;
long timerProgress;
Change your restProgress() method like below, or you can add new method pauseTimer().
public void restTimer(){
//This is where I want to set the text.
updateTimer((int) timerProgress/1000);
startBtn.setText("START!");
timerSeekBar.setEnabled(true);
countDownTimer.cancel();
timerSeekBar.setProgress((int) timerProgress/1000);
counterisActive = false;
}
Know add this line to your override method onTick.
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
// add this line for store progress timer.
timerProgress = millisUntilFinished;
}
You can add another button one for pause and other for rest Timer.
Try replacing timerTv.setText(minutes + " : " + secondString ); with
runOnUiThread(new Runnable() {
#Override
public void run() {
timerTv.setText(minutes + " : " + secondString );
}
});
If you try to update the UI mid-thread, it will wait until the current thread has finished before updating the text.
In my app, i'm using two different CountDownTimers that have same values. I have two buttons to control them but when i press the button twice, it starting from the beginning. I want to keep its last value.
Here is my code:
t1 = new CountDownTimer(white, 1000) {
#Override
public void onTick(long l) {
btnWhite.setText("seconds remaining: " + l / 1000);
white = l;
}
#Override
public void onFinish() {
}
};
t2 = new CountDownTimer(black, 1000) {
#Override
public void onTick(long l) {
btnBlack.setText("seconds remaining: " + l / 1000);
black = l;
}
#Override
public void onFinish() {
}
};
btnBlack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
t1.start();
t2.cancel();
}
});
btnWhite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
t2.start();
t1.cancel();
}
});
I have tested this and it works!
I have two TextViews and two Buttons. The black button is next to the black text view and the white button is next to the white text view.
First I declare the important constants.
//contains the elapsed time for each of the timers
long blackElapsed=0,whiteElapsed=0;
//contains the total time with which we start new timers
long totalWhite = 30000;
long totalBlack = 30000;
Next I initialise the CountDownTimers. Whatever you put in here doesn't matter. I only have this so that the timers will be initialised with some value.
The reason is that they have to be initialised in order to be able to .cancel() them later in the OnClickListeners.
black = new CountDownTimer(totalWhite, 1000){
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
}
};
white = new CountDownTimer(totalBlack, 1000){
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
}
};
Finally the OnClickListeners for the buttons. (W is white textView and B is black textView and b is black button and w is white button)
w.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
black.cancel();
//using the elapsed time to start a new timer
totalBlack = totalBlack - blackElapsed;
//this preserves milliseconds by ticking every millisecond
white = new CountDownTimer(totalBlack, 1){
#Override
public void onTick(long l) {
B.setText(l+"");
blackElapsed=totalBlack-l; //updating the elapsed time
}
#Override
public void onFinish() {
}
}.start();
}
});
//we do a similar thing with the other player's button
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
white.cancel();
totalWhite = totalWhite - whiteElapsed;
black = new CountDownTimer(totalWhite, 1){
#Override
public void onTick(long l) {
W.setText(l+"");
whiteElapsed=totalWhite-l;
}
#Override
public void onFinish() {
}
}.start();
}
});
I have checked your code.
It is obvious because your timers initialised with default values. when you start again it won't take new values of white/black.
To achieve what you want you have to initialise timer with new values before starting it.
I have done some correction in your code. you can check that out.
Make Two methods
public void timerStart1(long timeLengthMilli) {
t1 = new CountDownTimer(timeLengthMilli, 1000) {
#Override
public void onTick(long l) {
isRunning1 = true;
tv1.setText("seconds remaining: " + l / 1000);
white = l;
}
#Override
public void onFinish() {
isRunning1 = false;
}
}.start();
}
public void timerStart2(long timeLengthMilli) {
t2 = new CountDownTimer(timeLengthMilli, 1000) {
#Override
public void onTick(long l) {
isRunning2 = true;
tv2.setText("seconds remaining: " + l / 1000);
black = l;
}
#Override
public void onFinish() {
isRunning2 = false;
}
}.start();
}
and set setOnClickListener like this
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isRunning1) {
isRunning2 = false;
timerStart1(white);
if (t2 != null)
t2.cancel();
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isRunning2) {
isRunning1 = false;
timerStart2(black);
if (t1 != null)
t1.cancel();
}
}
});
UPDATE :
Please check updated code and take these extra variables
boolean isRunning1 = false, isRunning2 = false;
Hope this will help you.
Happy Coding.
In my game the user gets a point when he clicks a button within five seconds. Now I want the timer to decrease the time with every point the user gets - so e.g. with zero points the user has five seconds, and when he has one point he gets only 4.5 seconds to click it again and get the second point. Do I solve it with a for loop?
public class GameScreen extends Activity {
public int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Button count = (Button) findViewById(R.id.button1);
text = (TextView) this.findViewById(R.id.textView3);
tvscore = (TextView) findViewById(R.id.score);
timer();
}
public void gameover() {
Intent intent = new Intent(this, GameOverScreen.class);
startActivity(intent);
}
public void onClick (View view) {
score++;
tvscore.setText(String.valueOf(score));
timer();
}
public void timer(){
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("Too slow.");
gameover();
}
}.start();
}
}
What about doing this:
public void timer(float time) {
new CountDownTimer(time, 10) {
// YOUR CODE
}
}
public void onClick (View view) {
score++;
tvscore.setText(String.valueOf(score));
timer(Math.max(5000-score*500, 2000));
}
I suppose each click (score) will decrease the time with 500 millis...
Limit - Math.max(a, b) will choose the biggest value. Means when 5000-score*500 will be lower than 2000, it will choose 2000 millis instead
Only timer method:
public void timer() {
float time = Math.max(5000-score*500, 2000)
new CountDownTimer(time, 10) {
// YOUR CODE
}
}
I am trying to start a timer when activity created and be able to reset the timer back from zero if the same button is pressed but every time I press the button that initiates the set Interval it seems to be creating a new interval and not resetting the one that was already creating. Can someone help please? Here is my code
timer = (TextView) findViewById(R.id.timer_value);
Count = new CountDownTimer(time, 1000) {
public void onTick(long millisUntilFinished) {
timer.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
timer.setText("OUT OF TIME!");
if (time < 10000) {
time = 10000;
}
AlertDialog.Builder builder = new AlertDialog.Builder(
TicTacToe.this);
builder.setMessage("You are Out of Time").setPositiveButton(
"Replay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// reset the game environment.
Count.onFinish();
// Count.cancel();
Count.start();
new_game(player_name_1);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}.start();
you can use timers
//in global
Timer myTimer
/**
* its kills runnable
*/
public void stopTimer(){
//handler.removeCallbacks(null); //it resets all timer which handler holds
myTimer.cancel();
}
public void setTimer(int time){//give it 5 for 5 secs
final Runnable Update = new Runnable() {
public void run() {
//do sth
}
};
myTimer = new Timer();
myTimerTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 1000, time*1000);
}
If you want to restart your timer, remove Count.onFinish();
Update:
I replaced AlertDialog with a new thread and here is the code that works on my emulator
public class MainActivity extends Activity
{
int time = 10000;
CountDownTimer Count;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView timer = (TextView) findViewById(R.id.timer);
Count = new CountDownTimer(time, 1000) {
public void onTick(long millisUntilFinished) {
timer.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
timer.setText("OUT OF TIME!");
if (time < 10000) {
time = 100000;
}
}
}.start();
}
public void buttonClicked(View view)
{
Log.i("Timer", "Resetting timer");
Count.cancel();
Count.start();
}
}