How to create a countdown stopwatch in java - java

When I call the function() I want to have a chance to cancel the SOS call, If I click the button.
Basically It reads Integer.parseInt(cancelTime.getText().toString()) that has a time in second to be able to cancel.
My problem is that I'm trying to show like a countdown of the time elapsed from Integer.parseInt(cancelTime.getText().toString()) to 0 and it appears a huge number: ex: 10546468261
private void function()
{
startTime = System.currentTimeMillis();
Runnable runnable = new Runnable() {
#Override
public void run() {
double elapsedTime = (System.currentTimeMillis() - startTime)/1000;
alertButton.setText("CANCEL THE SOS: " + (int)elapsedTime);
alertButton.setBackgroundColor(Color.parseColor("#FF0000"));
}
};
Handler handler = new Handler();
handler.postDelayed(runnable, Integer.parseInt(cancelTime.getText().toString()));
}

I have modified your code, This may help you.
private void function()
{
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
alertButton.setText("seconds remaining: " + millisUntilFinished / 1000);
alertButton.setBackgroundColor(Color.parseColor("#FF0000"));
}
public void onFinish() {
alertButton.setText("Cancel SOS");
}
}.start();
}
Modify new CountDownTimer(30000, 1000) as per your need
Parameter 1:- long millisInFuture
Parameter 2:- long countDownInterval

Related

How to implement decreasing counter in textView.setText using for loop?

I'm trying to implement a decreasing counter using for loop in android java. I have used handler & runnable to delay for loop iteration and I want the counter to start from 80 and end on 0, but in output, I'm getting counter from 0 to 80. In short, the reverse is required.
This is my code,
TextView totalpoints = (TextView) findViewById(R.id.txttotalpoints);
Handler handler1 = new Handler();
for (int count = 80;count>=0; count--){
int finalCount = count;
handler1.postDelayed(new Runnable() {
#Override
public void run() {
totalpoints.setText("Total Points : "+ finalCount);
System.out.println("This is in newpointsCounter" + finalCount);
}
}, 1000 * count);
}
Current output => Start from 0 & end on 80
Required output => Start from 80 & end on 0
You can user CountDownTimer as:
CountDownTimer countDownTimer = new CountDownTimer(80000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
//TODO on each interval, print your count
}
#Override
public void onFinish() {
//TODO on finish of timer, you will get notified
}
};
countDownTimer.start();
Try this :
final Handler handler = new Handler();
int count = 80;
final Runnable runnable = new Runnable() {
public void run() {
totalpoints.setText("Total Points : " + count);
Log.d(TAG, "count: " + count);
if (count-- > 80) {
handler.postDelayed(this, 5000);
}
}
};
handler.post(runnable);
Also I would recommend using log tags rather than system.println for android
No need to use handler, Android provides CountDownTimer itself just use it.
// For Java
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
System.out.println( millisUntilFinished / 1000)
}
public void onFinish() {
//work done
}
}.start();
// For kotlin
object : CountDownTimer(30000, 1000) {
override fun onTick(millisUntilFinished: Long) {
System.out.println( millisUntilFinished / 1000)
}
override fun onFinish() {
}
}.start()

how to make program read stopwatch and then print statement in another textview box when time reaches that second

I want to make a stopwatch. when my stopwatch reaches 1 minute I want it to print a statement, how can i make it do this?
I am using android studio(java), Here is a bit of my code:
Button btnStart,btnPause,btnLap;
TextView txtTimer;
Handler customHandler = new Handler();
LinearLayout container;
TextView lt;
long startTime=0L,timeinMilliseconds=0L,timeSwapBuff=0L,updateTime=0L;
Runnable updateTimerThread = new Runnable() {
#Override
public void run() {
timeinMilliseconds = SystemClock.uptimeMillis() -startTime;
updateTime = timeSwapBuff+timeinMilliseconds;
int secs=(int) (updateTime/1000);
int mins=secs/60;
secs%=60;
int milliseconds=(int) (updateTime%1000);
String s = "" + mins + ":" + String.format("%02d",secs) + ":" + String.format("%03d",milliseconds);
txtTimer.setText (s);
customHandler.postDelayed(this,0);
}
};
If you just want to setText after some X minutes just create a method like this:
private void printText(int minutes) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//do you setText here
}
}, minutes * 1000);
}
and use it like:
printText(1);
Update:
Chronometer is exactly what you are looking for.
It extends TextView, so just replace your timer textview with Chronometer
mChronometer = findViewById(R.id.chronometer2);
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
mChronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometer) {
long elapsedMillis = SystemClock.elapsedRealtime() - mChronometer.getBase();
int secs = (int) (elapsedMillis/1000);
int mins = secs/60;
if (mins == 1) {
mChronometer.stop();
anotherTextVeiw.setText("the 1 minute mark has passed");
}
}
});
You don't have to deal with Handler and Runnable with this approach

android - countdown timer is not canceling

In my app the user gets a point, when he clicks a button within 5 seconds. After that the timer should be canceled and restart. The problem I have is that the timer countinues counting down until it restarts. Is it set up wrong, or doesn't cancel(); stop the timer at all?
public class MainActivity extends AppCompatActivity {
Button btn;
TextView text;
TextView scoretv;
private static final String FORMAT = "%02d:%02d";
public int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scoretv = (TextView) findViewById(R.id.textView3);
btn = (Button) findViewById(R.id.button1);
text = (TextView) findViewById(R.id.textView2);
}
public void onClick(View view) {
score++;
scoretv.setText(String.valueOf(score));
load();
}
private void load() {
// TODO Auto-generated method stub
new CountDownTimer(5000, 10) { // adjust the milli
// seconds here
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))));
}
public void onFinish() {
text.setText("GameOver.");
cancel();
}
}.start();
}
}
Because you're calling cancel() in onFinish, the timer won't stop when the user clicks the button. What will happen instead is that the button will start a 5 second CountDownTimer and at the end of the timer, cancel() will be called. But what's the point of cancelling a timer when it's already finished?
To fix this, I'd suggest making a global instance of a CountDownTimer object, instantiate it in the onCreate method, and cancel it in the onClick method.
First, add this to your global scope,
CountDownTimer timer;
Then, add what you originally had before in the load method to your onCreate,
timer = new CountDownTimer(5000, 10) { // adjust the milli
// seconds here
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))));
}
public void onFinish() {
text.setText("GameOver.");
//cancel(); <-this is redundant
}
}.start();
And call timer.cancel() in your onClick method,
public void onClick(View view) {
score++;
scoretv.setText(String.valueOf(score));
//load(); <-unnecessary
timer.cancel();
}
Lastly, I'd suggest getting rid of load since it's sort of unnecessary at this point.
Define variable
private final long timeLeftInMillis=60000;
Create class
public void startCountDown() {
countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
//Edit text set with time remaining
int seconds = (int) (millisUntilFinished / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
etime.setText( String.format("%02d", minutes)
+ ":" + String.format("%02d", seconds));
}
#Override
public void onFinish() {
}
}.start();
}
I used this in a quiz app to reset timer when an answer is given. Therefore I called timer from the class that I used to add a new question.
private void newQuestion(){
if (countDownTimer!=null){
countDownTimer.cancel();
}
getNextQuestion();
}

Running a method every second starting on button press

I need a timer to start any time I press a button (on the button itself) that shows how many seconds it's been since it's pressed in real time. Whenever it's pressed again, timer is reset to 0 and starts incrementing again
I know this isn't the way to do it, the button works fine but the timer should be in onCreate? I'm not sure how this is supposed to work with a button
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadedImg = (ImageView) findViewById(R.id.imageView);
}
public void clickAsync(View view) {
new ImageDownloader().execute(downloadUrl);
int seconds = 0;
Button button = (Button) view;
button.setText("Seconds since clicked: " + seconds);
Timer timer = new Timer();
//each time button is clicked, time is reset to 0 and increments in real time
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
seconds = 0;
seconds++;
button.setText("Seconds since clicked: " + seconds);
}
}, 0, 1000);
}
}
Another easy way to do this is to use Handler
mHandler = new Handler();
Just call updateSec();method on click of a button it'll update sec in interval of one seconds
Runnable UpdateRunnable = new Runnable() {
#Override
public void run() {
updateSec();
}
};
public void updateSec() {
mSeconds++;
mHandler.postDelayed(UpdateRunnable, 1000);
}
Example
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mSeconds = 0;
updateSec();//it'll update sec variable every second.
}
});
try this: use a handler
long startTime = 0;
long elapsedTime ;
//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;
int hours = minutes / 60;
seconds = seconds % 60;
//textview for displaying time..
timerTextView.setText(String.format("%d:%02d:%02d", hours, minutes, seconds));
timerHandler.postDelayed(this, 1000);
}
};
b.setOnClickListener(new View.OnClickListener() { //b is your button
#Override
public void onClick(View v) {
Button b = (Button) v;
if (b.getText().equals("Stop")) {
elapsedTime = System.currentTimeMillis() - startTime;
timerHandler.removeCallbacks(timerRunnable);
b.setText("Resume");
} else {
startTime = System.currentTimeMillis() - elapsedTime;
timerHandler.postDelayed(timerRunnable, 0);
Calendar cs = Calendar.getInstance();
System.out.println("Current time => " + cs.getTime());
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
String formattedDate = df.format(cs.getTime());
timerTextView.setText(formattedDate);
b.setText("Stop");
}
}
});
it will calculate the elapsed time and show time after stop...
You can use threads:
#Override
public void onClick(View view){
switch(view.getId()){
case R.id.button:
new Thread(new Runnable() {
#Override
public void run() {
try{
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
count++;
textView.post(new Runnable() {
#Override
public void run() {
textView.setText(count + "");
}
});
}
}
}).start;
break;
}
}
the view must be updated on main thread, and so you need to use post() method that has runnable instance as parameter.
Alternatively, you can also use AsyncTask.

synchronized countdown timer- android development

I have an app that has one countdown timer that should show up the same for every user when they open the app. In order to do this, I have based the time that the users' phones show on Epoch time. I do the following calculations to (what I thought would...) ensure that each phone shows the same time, and that the countdown clock is continuous and accurate. However, every time I open the app up, the clock is at a totally different time, when I think it should be continuously counting down and resetting. What's wrong? I have included my code below:
private static final int COUNTDOWN_DURATION = 30; //time in seconds
private static final long BASE_TIME = 1470729402L; //an arbitrary Epoch time that I have picked as a reference point
private TextView tvTimer;
private Long currentTimeMillis;
private int finalTime;
private boolean firstTime;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
//set up basics
...
//set up timer
tvTimer = (TextView) findViewById(R.id.tvTimer);
firstTime = true;
setCurrentTime();
}
private void setCurrentTime() {
currentTimeMillis = System.currentTimeMillis();
long currentTimeSecs = currentTimeMillis/1000;
long timeDiff = currentTimeSecs - BASE_TIME;
//determines what spot the countdown timer is at when the app is started
finalTime = (int) (timeDiff % COUNTDOWN_DURATION);
resetTimer();
}
public void resetTimer(){
if (firstTime) {
CountDownTimer countDownTimer = new CountDownTimer(finalTime * 1000, 1000) {
public void onTick(long millisUntilFinished) {
tvTimer.setText(" " + millisUntilFinished / 1000 + " ");
}
public void onFinish() {
resetTimer();
}
};
countDownTimer.start();
firstTime = false;
}
else {
CountDownTimer countDownTimer = new CountDownTimer(COUNTDOWN_DURATION * 1000, 1000) {
public void onTick(long millisUntilFinished) {
tvTimer.setText(" " + millisUntilFinished / 1000 + " ");
}
public void onFinish() {
resetTimer();
}
};
countDownTimer.start();
}
}

Categories