I am a beginner in android, and I want to make a simple chess-timer clock. Here, I have taken two buttons. If I click on the first one the second button should start a countdown or vice-versa. But pause button is not working properly it pauses only one time second time it will not pause. Here I attached my code.
package com.example.jaydeep.practicework.chessClock;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.jaydeep.practicework.R;
public class Main8Activity extends AppCompatActivity {
Button button11,button22;
CountDownTimer count,count1;
int s1=60,s2=60;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main8);
button11 = (Button) findViewById(R.id.Button11);
button22 = (Button) findViewById(R.id.Button22);
button11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
button11.setEnabled(false);
reverseTimer1(s2, button22);
}
});
button22.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
button22.setEnabled(false);
reverseTimer(s1, button11);
}
});
}
public void reverseTimer(int Seconds,final Button button){
button11.setEnabled(true);
count= new CountDownTimer(Seconds* 1000+1000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000);
s1=seconds;
int minutes = seconds / 60;
seconds = seconds % 60;
button.setText( String.format("%02d", minutes)
+ ":" + String.format("%02d", seconds));
}
public void onFinish() {
button.setText("Time Up!!!");
}
};
count.start();
}
public void reverseTimer1(int Seconds,final Button button){
button22.setEnabled(true);
count1= new CountDownTimer(Seconds* 1000+1000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000);
s2=seconds;
int minutes = seconds / 60;
seconds = seconds % 60;
button.setText( String.format("%02d", minutes)
+ ":" + String.format("%02d", seconds));
}
public void onFinish() {
button.setText("Time Up!!!");
}
};
count1.start();
}
}
cancel();
You need this code
if(isPaused || isCanceled)
{
//If the user request to cancel or paused the
//CountDownTimer we will cancel the current instance
cancel();
}
This link should help you understand:
https://android--examples.blogspot.com.au/2015/04/android-countdowntimer-start-pause.html
Related
I am trying to add numbers to an already existing number based on a formula when a CountDownTimer is running. The timer is working, but the number(amount) crashes the app
public class Main extends AppCompatActivity {
TextView Time;
ImageButton button;
TextView amount;
TextView rate, milltime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Time = findViewById(R.id.Time);
button = findViewById(R.id.button);
amount = findViewById(R.id.Amount);
rate = findViewById(R.id.Ratenumber);
milltime = findViewById(R.id.milltime);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CountDownTimer(10000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
NumberFormat f = new DecimalFormat("00");
long hour = (millisUntilFinished / 3600000) % 24;
long min = (millisUntilFinished / 60000) % 60;
long sec = (millisUntilFinished / 1000) % 60;
Time.setText(f.format(hour) + ":" + f.format(min) + ":" + f.format(sec));
}
#Override
public void onFinish() {
Time.setText("Click to start");
}
}.start();
new CountDownTimer(10000,1){
#Override
public void onTick(long millisUntilFinished) {
milltime.setText(""+millisUntilFinished /1000 + millisUntilFinished %1000);
}
#Override
public void onFinish() {
milltime.setText("Did it work?");
}
}.start();
int n1 = Integer.parseInt(milltime.getText().toString());
int n2 = Integer.parseInt(rate.getText().toString());
int n3 = (1000 - n1) * n2;
amount.setText(""+String.valueOf(n3));
}
});
}
What I am trying to get, is the amount to increase as the timer runs based on the rate.
without the xml I'm only assuming here
First of all, the calculation code is on the button click and out of the counter scope your crash might be because of the Integer parsing
where your milltime and rate could be empty and that's what making it crash due to NumberFormatException
I am using following code to run a timer in my Android App.
I want to stop the Timer exactly when the time reaches to
1 Minute
2 Minute
3 Minute
and so on.
But I am not able to understand how to do it.
Any Help Will be appreciated.
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView timerTextView;
long startTime = 0;
//runs without a timer by reposting this handler at the end of the runnable
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.activity_main);
timerTextView = (TextView) findViewById(R.id.text);
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");
}
}
Why not use the CountDownTimer class?
You can simply instantiate it as:
int bigTime = 1000000000;
//1000 is ms after which the timer ticks (that is, the method gets called and so, you can update your view)
CountDownTimer countDownTimer = new CountDownTimer(bigTime, 1000) {
public void onTick(long millisUntilFinished) {
updateTime();
//you can write the code to update your view in this method
}
#Override
public void onFinish() {
Log.i("Get a life bro..."," 31 years have passed!");
}
};
Now, in your onCreate() method, according to the clicklisteners on your start/stop button, you can simply start or stop the timer:
countDownTimer.start();
if(seconds == 0 && minutes > 0) {
// get the values of seconds and minutes from the view.
countDownTimer.cancel();
}
Just in case you want to pause the timer and start from the paused time, you can store the value of the time in milliseconds, stop the timer and restart it after adding the value you stored.
I'm newbie in android programming..
I have a media player in my activity to play a sound.
I want to do some code on a special time that the media player is playing. I mean I want to do code1 during media player is in 0 to 5sec, and do code2 during 5 to 14 and do code3 during 14 to 18sec.
here's my timer code and I don't know how to run my codes on special times..
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView timerTextView;
long startTime = 0;
//runs without a timer by reposting this handler at the end of the runnable
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.activity_main);
timerTextView = (TextView) findViewById(R.id.text);
Button b = (Button) findViewById(R.id.button1);
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.button1);
b.setText("start");
}
}
This isn't the most elegant solution, especially if all your time blocks will be exactly 5 seconds apart but if you set initalTime when the media player starts, it should work. Further documentation for uptimeMillis() and other Android timer methods are linked here
int initialTime= SystemTimer.uptimeMillis();
while (mediaIsRunning){
int currentTime=SystemTimer.uptimeMillis();
int elapsed=currentTime-initialTime;
if (elapsed<=5000){ // 5 seconds
//your code 1
}
else if (elapsed<=10000){ //10 seconds
//code 2
}
//etc ...
}
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 all, I'm trying to get my CountDownTimer to autoreset back to it's original time after the time reaches zero. Like an infinite loop. Here is the code I have so far (there are 3 timers in total):
package com.android.countdown;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class countdown extends Activity {
public String formatTime(long millis) {
String output = "00:00";
long seconds = millis / 1000;
long minutes = seconds / 60;
seconds = seconds % 60;
minutes = minutes % 60;
String secondsD = String.valueOf(seconds);
String minutesD = String.valueOf(minutes);
if (seconds < 10)
secondsD = "0" + seconds;
if (minutes < 10)
minutesD = "0" + minutes;
output = minutesD + " : " + secondsD;
return output;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Declare Start/Stop button
Button btnstart = (Button)findViewById(R.id.btnstart);
Button btnstop = (Button)findViewById(R.id.btnstop);
//Declare Text fields to show time left
final TextView mCounter1TextField=(TextView)findViewById(R.id.counter1);
final TextView mCounter2TextField = (TextView)findViewById(R.id.counter2);
final TextView mCounter3TextField=(TextView)findViewById(R.id.counter3);
//Counter 1
final CountDownTimer Counter1 = new CountDownTimer(120000 , 1000) {
public void onTick(long millisUntilFinished) {
mCounter1TextField.setText("Seconds left: " + formatTime(millisUntilFinished));
}
public void onFinish() {
mCounter1TextField.setText("Finished!");
}
};
//Counter 2
final CountDownTimer Counter2 = new CountDownTimer(80000 , 1000) {
public void onTick(long millisUntilFinished) {
mCounter2TextField.setText("Seconds left: " + formatTime(millisUntilFinished));
}
public void onFinish() {
mCounter2TextField.setText("Finished!");
}
};
//Counter 3
final CountDownTimer Counter3 = new CountDownTimer(10000 , 1000) {
public void onTick(long millisUntilFinished) {
mCounter3TextField.setText("Seconds left: " + formatTime(millisUntilFinished));
}
public void onFinish() {
mCounter3TextField.setText("Finished!");
}
};
//Start Button
btnstart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Counter1.start();
Counter2.start();
Counter3.start();
}
});
//Stop Button
btnstop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Counter1.cancel();
Counter2.cancel();
Counter3.cancel();
}
});
}
}
I can't figure what to put inside onFinish()
Put the CounterX.start() in the respective onFinish()
//Counter 1
final CountDownTimer Counter1 = new CountDownTimer(120000 , 1000) {
public void onTick(long millisUntilFinished) {
mCounter1TextField.setText("Seconds left: " + formatTime(millisUntilFinished));
}
public void onFinish() {
mCounter1TextField.setText("Finished!");
Counter1.start();
}
};