Issues with countdown timer android studio - java

I'm very new to Java and and I'm trying to make an activity that calls an countdown timer from 5:00 minutes to 0. But, I'm having some issues. I tried every example code out there. Can you guys help me?
import androidx.appcompat.app.AppCompatActivity;
import java.util.Locale;
public class Main4Activity extends AppCompatActivity {
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();

Fixed!
int minute;
long min;
TextView tv_timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
tv_timer=findViewById(R.id.contador);
minute=Integer.parseInt("5");
min= minute*60*1000;
counter(min);
}
private void counter(long min) {
CountDownTimer timer = new CountDownTimer(min, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000) % 60;
int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
tv_timer.setText(String.format("%d:%d", minutes, seconds));
}
public void onFinish() {
Toast.makeText(getApplicationContext(), "Your time has been completed",
Toast.LENGTH_LONG).show();
}
};
timer.start();
}
}

Related

How i can make it without bug - Java

I have a time counter bug in the game, how to fix it?
In my game, when there are 6 seconds left, the timer turns red and the animation is played, but sometimes the code freezes :(
It is this code that is bugging me, how to implement it differently:
if (mTimeLeftInMillis == 6000){
mTextViewCountDown.setTextColor(Color.RED);
mTextViewCountDown.startAnimation(zooming_second);
soundPlay(watch);
}
Here is the detailed code:
private void startTimer() {
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
if (mTimeLeftInMillis == 6000){
mTextViewCountDown.setTextColor(Color.RED);
mTextViewCountDown.startAnimation(zooming_second);
soundPlay(watch);
}
int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.ENGLISH, "%02d:%02d", minutes, seconds);
mTextViewCountDown.setText(timeLeftFormatted);
mTimerRunning = true;
}
#Override
public void onFinish() {
mTimerRunning = false;
TimeOutDialog();
soundPlay(time_out_sound);
mediaPlayer1.stop();
tadam_false.stop();
tadam_true.stop();
watch.stop();
mTextViewCountDown.clearAnimation();
}
}.start();
}

Change text from a class out

I created a simple Java class. This should spend the time. With System.out.println it works too! But how can I inform a certain TextView that it should also change?
Countdown_Test.java
public class Countdown_test {
private static long START_TIME_IN_MILLIS;
private CountDownTimer mCountDownTimer;
private boolean mTimerRunning;
private long mTimeLeftInMillis;
//private TextView timer;
public Countdown_test(long start_time) {
START_TIME_IN_MILLIS = start_time;
mTimeLeftInMillis = START_TIME_IN_MILLIS;
//timer = findViewById(R.id.timer); dosen't work
}
public void startTimer() {
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
mTimerRunning = false;
}
}.start();
mTimerRunning = true;
}
public void updateCountDownText() {
int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
System.out.println(timeLeftFormatted);
}
}
MainActivity.java
Countdown_test ct = new Countdown_test(600000);
button_start.setOnClickListener(v -> {
ct.startTimer();
});
ct.updateCountDownText();
You could write an interface, a TimeLeftListener with a method onTimeLeftChanged(String timeleft). Then your activity extends TimeLeftListener and implements the onTimeLeftChanged()-method.
This is where you update your views.
When you initiate your CountDownTest you pass the activity like this.
Countdown_test ct = new Countdown_test(600000, this);
And create al listener in you CountDownTest-class like this
myTimeLeftListener =(TimeleftListener)activity;
Then in your updateCountDownText()-Method you put
myTimeLeftListener.onTimeLeftChanged(timeleft)
You could also use ViewModel and LiveData.

Counting up 0 to 100

CountDown 0 to 100 Android
I'm only beginner with android can you help me guys with this.
The Result must be the end of the countdown.
for example, the result value is 75 the countdown will start to 0 ends to 75
mCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showResult();
new CountDownTimer(30000, 100){
public void onTick(long millisUntilFinished){
waveLoadingView.setProgressValue(counter);
waveLoadingView.setCenterTitle(String.format("%d%%",result)); //result is the value from randomize 60 to 80 .
result++;
}
public void onFinish(){
}
}.start();
}
});
// result varible define as a public
long result = 80;
mCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CountDownTimer(result * 1000, 100) {
public void onTick(long millisUntilFinished) {
// its start with 1 if you want start with 0 then replace with below code
//int sec = (int) (result - (millisUntilFinished / 1000)-1);
int sec = (int) (result - (millisUntilFinished / 1000));
waveLoadingView.setProgressValue(sec);
waveLoadingView.setCenterTitle(String.valueOf(result)); //result is the value from randomize 60 to 80 .
}
public void onFinish() {
}
}.start();
}
});
Try below code
mCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showResult();
new CountDownTimer(result*1000, 1000){
public void onTick(long millisUntilFinished){
waveLoadingView.setProgressValue(counter);
waveLoadingView.setCenterTitle(String.format("%d%%",newResult)); //newResult is temp value initialize with 0
newResult++;
}
public void onFinish(){
}
}.start();
}
});
You simply need to use the matching parameters when instantiating the CountDownTimer for your use case, take a look for CountDownTimer constructor method CountDownTimer(long millisInFuture, long countDownInterval). When you want to create a count down from 0 to 100 with 1 second step, you can construct your code like this:
final long ONE_SECOND = 1000;
final long ONE_HUNDRED_SECOND = 100 * ONE_SECOND;
new CountDownTimer(ONE_HUNDRED_SECOND, ONE_SECOND){
public void onTick(long millisUntilFinished) {
int second = millisUntilFinished / ONE_SECOND;
int counter = second - 1;
// do something with the counter value
}
public void onFinish() {
// do something when we finished the count down.
}
}.start();

Count down timer how to implement onfinish method

I have a countdown timer that i want to implement on finish method or some kind of code so that when the timer stops, the text views change to Time's up and another method is initiated (in the activity).
To clarify, the timer is given a starting number that counts down from, to zero in format of xx:xx.
The class of the timer :
public class countdown_timer {
private long pls;
private long millisInFuture;
private long countDownInterval;
private boolean status;
public countdown_timer(long pMillisInFuture, long pCountDownInterval) {
this.millisInFuture = pMillisInFuture;
this.countDownInterval = pCountDownInterval;
this.pls = pMillisInFuture;
status = false;
Initialize();
}
public void Stop() {
status = false;
}
public void Reset() {
millisInFuture = pls;
}
public long getCurrentTime() {
return millisInFuture;
}
public void Start() {
status = true;
}
public void Initialize()
{
final Handler handler = new Handler();
Log.v("status", "starting");
final Runnable counter = new Runnable(){
public void run(){
long sec = millisInFuture/1000;
if(status) {
if(millisInFuture <= 0) {
Log.v("status", "done");
} else {
Log.v("status", Long.toString(sec) + " seconds remain");
millisInFuture -= countDownInterval;
handler.postDelayed(this, countDownInterval);
}
} else {
Log.v("status", Long.toString(sec) + " seconds remain and timer has stopped!");
handler.postDelayed(this, countDownInterval);
}
}
};
handler.postDelayed(counter, countDownInterval);
}
The activty that the timer is used:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_game_2);
//...find views
mycounterup = new countdown_timer(startcard, 1000);
mycounterdown = new countdown_timer(startcard, 1000);
RefreshTimer();
mycounterdown.Start();
public void RefreshTimer()
{
final Handler handler = new Handler();
final Runnable counter = new Runnable(){
public void run(){
int minutes_up_start = (int) (mycounterup.getCurrentTime() / 1000) / 60;
int seconds_up_start = (int) (mycounterup.getCurrentTime() / 1000) % 60;
String time_2_up_start_formatted = String.format(Locale.getDefault(), "%02d:%02d", minutes_up_start, seconds_up_start);
card_2_up.setText(time_2_up_start_formatted);
int minutes_down_start = (int) (mycounterdown.getCurrentTime() / 1000) / 60;
int seconds_down_start = (int) (mycounterdown.getCurrentTime() / 1000) % 60;
String card_2_down_start_formatted = String.format(Locale.getDefault(), "%02d:%02d", minutes_down_start, seconds_down_start);
card_2_down.setText(card_2_down_start_formatted);
handler.postDelayed(this, 100);
}
};
handler.postDelayed(counter, 100);
}
You can use CountDownTimer:
new CountDownTimer(endsIn * 1000, 1000) {
public void onTick(long millisUntilFinished) {
timerTextView.setText(String.valueOf(millisUntilFinished/1000);
}
public void onFinish() {
}
}.start();
OR:
extend CountDownTimer class:
public class countdown_timer extends CountDownTimer {
TextView textView;
#Override
public void onTick(long millisInFuture) {
long sec = millisInFuture/1000;
if(millisInFuture <= 0) {
Log.v("status", "done");
} else {
Log.v("status", Long.toString(sec) + " seconds remain and timer has stopped!");
}
}
#Override
public void onFinish() {
if(textView != null){
// change text in your textview
}
}
public countdown_timer(long pMillisInFuture, long pCountDownInterval) {
super(pMillisInFuture, pCountDownInterval);
}
public countdown_timer(TextView textView, long pMillisInFuture, long pCountDownInterval) {
super(pMillisInFuture, pCountDownInterval);
this.textView = textView;
}
}
here is a two constructors, one of them is the same as is in your example and in second one you can pass also TextView object and use it in onFinish() method.
UPDATE 2:
Here is CountDownTimer in the Activity:
public class MainActivity extends AppCompatActivity {
TextView textView;
CountDownTimer mycounterdown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
long startcard = 10000;
textView = (TextView) findViewById(R.id.test);
mycounterdown = new CountDownTimer(startcard, 1000) {
#Override
public void onTick(long mycounterup) {
int minutes_up_start = (int) (mycounterup / 1000) / 60;
int seconds_up_start = (int) (mycounterup / 1000) % 60;
String time_2_up_start_formatted = String.format(Locale.getDefault(), "%02d:%02d", minutes_up_start, seconds_up_start);
textView.setText(time_2_up_start_formatted);
}
#Override
public void onFinish() {
// call here other methods from activity
testMethod();
}
};
mycounterdown.start();
}
public void testMethod(){
Toast.makeText(MainActivity.this, "Test Method called", Toast.LENGTH_SHORT).show();
}
}
UPDATE 3: if last tick is one, not zero change count down interval to 500 instead of 1000:
public class MainActivity extends AppCompatActivity {
TextView textView;
CountDownTimer mycounterdown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
long startcard = 10000;
textView = (TextView) findViewById(R.id.test);
mycounterdown = new CountDownTimer(startcard, 500) {
#Override
public void onTick(long mycounterup) {
int minutes_up_start = (int) (mycounterup / 1000) / 60;
int seconds_up_start = (int) (mycounterup / 1000) % 60;
String time_2_up_start_formatted = String.format(Locale.getDefault(), "%02d:%02d", minutes_up_start, seconds_up_start);
textView.setText(time_2_up_start_formatted);
}
#Override
public void onFinish() {
// call here other methods from activity
testMethod();
}
};
mycounterdown.start();
}
public void testMethod(){
Toast.makeText(MainActivity.this, "Test Method called", Toast.LENGTH_SHORT).show();
}
}
NOTE: take a look at this answer
First, extend CountDownTimer in your timer class.
public class countdown_timer extends CountDownTimer {
}
This allows you to implement some methods.
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
}
Also you must implement constructor that matches super class. You can also add some additional parameters. For example TextView
TextView textView;
public countdown_timer(long millisInFuture, long countDownInterval, TextView txt) {
super(millisInFuture, countDownInterval);
textView = txt;
}
The onFinish() is what you want. Also make sure you are using this class as a CountDownTimer. Then you will be able to start your timer.
Hope it helps.

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