How can I add variable to CountDownTimer in android studio? - java

I'm trying to use variable into the CountDownTimer constructor but the application doesn't work. Normally works with duration without a variable(like 10000). How Can I use a variable?
my code
private CountDownTimer countDownTimer = new CountDownTimer(duration, 1000) {
#Override
public void onTick(long l) {
txt_count.setText(String.valueOf(l / 1000));
progressBar.setProgress((int) l/ 1000);
}
#Override
public void onFinish() {
iscountering = false;
if(temp_question.getQuestions().size() !=(temp_position+1))
Do_Next_Question(temp_position,temp_question);
else
Toast.makeText(ObserverRoomActivity.this, "پایان آزمون", Toast.LENGTH_SHORT).show()
}
};
private void StartTimer(){
if(!iscountering){
iscountering = true;
countDownTimer.start();
}else{
iscountering = false;
countDownTimer.cancel();
}
}

I think you need to use timer like this:
private CountDownTimer countDownTimer;
private void createTimer(int duration) {
countDownTimer = new CountDownTimer(duration, 1000) {
#Override
public void onTick(long l) {
txt_count.setText(String.valueOf(l / 1000));
progressBar.setProgress((int) l/ 1000);
}
#Override
public void onFinish() {
iscountering = false;
if(temp_question.getQuestions().size() !=(temp_position+1))
Do_Next_Question(temp_position,temp_question);
else
Toast.makeText(ObserverRoomActivity.this, "پایان آزمون", Toast.LENGTH_SHORT).show()
}
};
}
private void StartTimer(){
if(!iscountering){
iscountering = true;
countDownTimer.start();
} else {
iscountering = false;
countDownTimer.cancel();
}
}
// Call this method to pass your duration for the timer
private void createAndStartTimer(int duration) {
createTimer(duration);
startTimer();
}

Related

My progressbar does not sync with my count down timer

Here I have made this method for starting my timer and the one below it updates the timer:
private void startTimer()
{
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
progress++;
pb.setProgress((int)progress*100/((int)millisUntilFinished/1000));
}
#Override
public void onFinish()
{
progress++;
pb.setProgress(100);
//Vibration
if (Build.VERSION.SDK_INT >= 26)
{
((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE));
Toast.makeText(MainActivity2.this,"Done",Toast.LENGTH_SHORT).show();
}
else
{
((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createWaveform(new long[]{150}, new int[]{VibrationEffect.EFFECT_CLICK},-1));
}
}
}.start();
}
private void updateCountDownText()
{
//time in minutes and seconds
int minutes = (int)(mTimeLeftInMillis/1000)/60;
int seconds = (int)(mTimeLeftInMillis/1000)%60;
//formating the above to appear as String
String timeLeftFormatted = String.format("%02d:%02d",minutes,seconds);
timer.setText(timeLeftFormatted);
}
"pb" is the name of my progressbar. It keeps finishing earlier than the countdown by 2 minutes and I don't know how to synchronize them. Also upon completion the vibration is not triggered for some reason even though it did before. "progress" is initialized as zero as a global variable.
Here is the solution:
long millisInFuture;
private void startTimer() {
millisInFuture = mTimeLeftInMillis;
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
long millisPassed = millisInFuture - mTimeLeftInMillis;
progress = (int) (millisPassed * 100 / millisInFuture);
pb.setProgress(progress);
}
#Override
public void onFinish() {
pb.setProgress(100);
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
VibrationEffect effect =
VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE);
vibrator.vibrate(effect);
Toast.makeText(MainActivity2.this, "Done", Toast.LENGTH_SHORT).show();
} else {
vibrator.vibrate(150);
}
}
}.start();
}
But I don't see when you initialize your progressbar.
If you set pb.max ( or setMax in Java ) = 100
And on each onTick call a method :
private changePb(long millisUntilFinished){
pb.progress = (millisUntilFinished / millisStartValue) * 100
}
Where millisStartValue was the first value you put in new CountDownTimer(mTimeLeftInMillis
And in onFinish, you don't have to put new value for progressbar.

How to make repeated countdown timer

I am making cutdown timer and I wanna reapeat it after break. For example I set timer fo 4 second after this 4 seconds I wanna have 10 second break and then i wanna have timer again for 4 minutes
My timer look like that
long millisInput = Long.parseLong(input) * 60000;
mButtonStartPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTimerRunning) {
pauseTimer();
} else {
startTimer();
}
});
mButtonReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetTimer();
}
});
}
private void setTime(long milliseconds) {
mStartTimeInMillis = milliseconds;
resetTimer();
closeKeyboard();
}
private void startTimer() {
mEndTime = System.currentTimeMillis() + mTimeLeftInMillis;
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimerRunning = true;
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
mTimerRunning = false;
updateWatchInterface();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(counter++ < 5){
startTimer();
}
}
},10000);
}
}.start();
updateWatchInterface();
}
private void pauseTimer() {
mCountDownTimer.cancel();
mTimerRunning = false;
updateWatchInterface();
}
private void resetTimer() {
mTimeLeftInMillis = mStartTimeInMillis;
updateCountDownText();
updateWatchInterface();
}
private void updateCountDownText() {
int hours = (int) (mTimeLeftInMillis / 1000) / 3600;
int minutes = (int) ((mTimeLeftInMillis / 1000) % 3600) / 60;
int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted;
if (hours > 0) {
timeLeftFormatted = String.format(Locale.getDefault(),
"%d:%02d:%02d", hours, minutes, seconds);
} else {
timeLeftFormatted = String.format(Locale.getDefault(),
"%02d:%02d", minutes, seconds);
}
mTextViewCountDown.setText(String.valueOf(counter + 1) +" - "+timeLeftFormatted);
}
private void updateWatchInterface() {
if (mTimerRunning) {
mEditTextInput.setVisibility(View.INVISIBLE);
mButtonSet.setVisibility(View.INVISIBLE);
mButtonReset.setVisibility(View.INVISIBLE);
mButtonStartPause.setText("Pause");
} else {
mEditTextInput.setVisibility(View.VISIBLE);
mButtonSet.setVisibility(View.VISIBLE);
mButtonStartPause.setText("Start");
if (mTimeLeftInMillis < 1000) {
mButtonStartPause.setVisibility(View.INVISIBLE);
} else {
mButtonStartPause.setVisibility(View.VISIBLE);
}
if (mTimeLeftInMillis < mStartTimeInMillis) {
mButtonReset.setVisibility(View.VISIBLE);
} else {
mButtonReset.setVisibility(View.INVISIBLE);
}
}
}
private void closeKeyboard() {
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("startTimeInMillis", mStartTimeInMillis);
editor.putLong("millisLeft", mTimeLeftInMillis);
editor.putBoolean("timerRunning", mTimerRunning);
editor.putLong("endTime", mEndTime);
editor.apply();
if (mCountDownTimer != null) {
mCountDownTimer.cancel();
}
}
#Override
protected void onStart() {
super.onStart();
SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
mStartTimeInMillis = prefs.getLong("startTimeInMillis", 600000);
mTimeLeftInMillis = prefs.getLong("millisLeft", mStartTimeInMillis);
mTimerRunning = prefs.getBoolean("timerRunning", false);
updateCountDownText();
updateWatchInterface();
if (mTimerRunning) {
mEndTime = prefs.getLong("endTime", 0);
mTimeLeftInMillis = mEndTime - System.currentTimeMillis();
if (mTimeLeftInMillis < 0) {
mTimeLeftInMillis = 0;
mTimerRunning = false;
updateCountDownText();
updateWatchInterface();
} else {
startTimer();
}
}
}
And after set for example one minute I wanna reapeat same time 5 times. ( IIIIIIIIIIIIIIIIIIIIIIIIIIII
Replace your code with this.
int timerMilliSecond = 4000;
CountDownTimer countDownTimer = new CountDownTimer(timerMilliSecond, 1000) {
#Override
public void onTick(long millisUntilFinished) {
tv2.setText("Przygotuj się:\n " + (millisUntilFinished / 1000));
}
public void onFinish() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
timerMilliSecond = 4 * 60000;
countDownTimer.start();
}
},1000);
}
}.start();
I hope it's helpful for you.
int counter = 0;
CountDownTimer countDownTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countDownTimer = new CountDownTimer(4000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
int rounded = (int) (((millisUntilFinished + 999) / 1000 ) * 1000); // 4000,3000,2000,1000 ....
tv2.setText("Przygotuj się:\n " + (rounded / 1000));
}
public void onFinish() {
tv2.setText("Przygotuj się:\n " + 0);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(counter++ < 5)
countDownTimer.start();
}
},10000); // repeat after ten seconds.
}
}.start();
}
if you don't want endless loop, you should use counter. So you can repeat five times.
#Override
public void onFinish() {
mTimerRunning = false;
updateWatchInterface();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(counter++ < 5){
mTimerRunning = true;
startTimer();
}
}
},60000);
}

Countdown timer does not stop when activity change

I have used class which have timer function. So i can reuse that code everytime whenever i want. Problem is when i move from one activity to another activity then timer should be reset but timer could not be finished and new timer will be start again. Here is my code
public class Utils {
Context mContext;
private static final String TAG = Utils.class.getSimpleName();
CountDownTimer mCountDownTimer = null;
boolean isRunning = false;
private Activity activityContext;
public Utils(Context context) {
this.mContext = context;
this.activityContext = (Activity) context;
}
public void resetTimer() {
if (isRunning) {
Log.d(TAG, "Timer is stopping now..######");
mCountDownTimer.cancel();
mCountDownTimer = null;
isRunning = false;
startCountDownTimer();
} else {
Log.d(TAG, "Timer is starting now..######");
startCountDownTimer();
}
}
public void stopCountDownTimer() {
if (mCountDownTimer != null) {
mCountDownTimer.cancel();
mCountDownTimer = null;
}
}
public void startCountDownTimer() {
mCountDownTimer = new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
Log.d(TAG, "Timer is ticking..!!!!");
isRunning = true;
}
public void onFinish() {
Log.d(TAG, "Timer is finished..!!!!");
isRunning = false;
try {
Intent launchIntent = mContext.getPackageManager()
.getLaunchIntentForPackage("com.#########.###");
activityContext.startActivity(launchIntent);
activityContext.finish();
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
In activity create method i call this resetTimer() but timer does not reset. I also call stopCountDownTimer() and result will be same. What am i missing here ?
SOLVED :
public class Utils {
Context mContext;
private static final String TAG = Utils.class.getSimpleName();
CountDownTimer mCountDownTimer = null;
boolean isRunning = false;
private Activity activityContext;
private final long startTime = 10 * 1000;
private final long interval = 1 * 1000;
public Utils(Context context) {
this.mContext = context;
this.activityContext = (Activity) context;
mCountDownTimer = new MyCountDownTimer(startTime, interval);
}
public void resetTimer() {
if (isRunning) {
Log.d(TAG, "Timer is stopping now..######");
mCountDownTimer.cancel();
mCountDownTimer = null;
mCountDownTimer = new MyCountDownTimer(startTime, interval);
isRunning = false;
Log.d(TAG, "Timer is stopped amd starting again..######");
mCountDownTimer.start();
// startCountDownTimer();
} else {
Log.d(TAG, "Timer is starting now..######");
// startCountDownTimer();
mCountDownTimer.start();
}
}
}
public void stopCountDownTimer() {
if (mCountDownTimer != null) {
mCountDownTimer.cancel();
mCountDownTimer = null;
}
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
Log.d(TAG, "Timer is finished..!!!!");
isRunning = false;
try {
Intent launchIntent = mContext.getPackageManager()
.getLaunchIntentForPackage("com.####.####");
activityContext.startActivity(launchIntent);
activityContext.finish();
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onTick(long millisUntilFinished) {
Log.d(TAG, "Timer is ticking..!!!!");
//Toast.makeText(mContext, ""+millisUntilFinished/1000, 50).show();
isRunning = true;
}
}
}

non-static method start() cannot be referenced from a static context

When I'm trying to add Start and Cancel in the button I get this error.
I looked into the Timer files but I didn't see anything
"error: non-static method start() cannot be referenced from a static context"
public int number;
public TextView textfield;
Button buton;
int x = 1;
Boolean y = false;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reading);
new CountDownTimer(100000, 1000) {
public void onTick(long millisUntilFinished) {
textfield.setText("Time: " + millisUntilFinished / 1000);
}
public void onFinish() {
textfield.setText("Time is up");
}
}.start();
textfield=(TextView)findViewById(R.id.Zamanlayici);
buton=(Button)findViewById(R.id.Click);
buton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//My Error is in there :(
if (y) {
CountDownTimer.start();
y= true;
}
else {
y = false;
CountDownTimer.cancel();
}
}
});
}
}
You are trying to use not static method like a static. Try to create a variable to store instance of CountDownTimer and call methods on it. Also doc: http://developer.android.com/reference/android/os/CountDownTimer.html
You need to create an instance of CountDownTimer, like so:
CountDownTimer timer = new CountDownTimer(100000, 1000){...}
Then, in the onClick method:
if (y) {
timer.start();
y= true;
}
else {
y = false;
timer.cancel();
}
You need to create an instance of CountDownTimer to call non-static methods from it.
CountDownTimer timer = new CountDownTimer();
timer.start();
Change your code to this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reading);
CountDownTimer timer = new CountDownTimer(100000, 1000) {
public void onTick(long millisUntilFinished) {
textfield.setText("Time: " + millisUntilFinished / 1000);
}
public void onFinish() {
textfield.setText("Time is up");
}
}
timer.start();
textfield=(TextView)findViewById(R.id.Zamanlayici);
buton=(Button)findViewById(R.id.Click);
buton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (y) {
timer.start();
y= true;
}
else {
y = false;
timer.cancel();
}
}
});
}

Android repeat CountDownTimer until end foreach loop

I want to repeat a CountDownTimer within a for loop until its execution complete. But CountDownTimer executes first index of for loop and it can not repeat again for next index.
for (final Question questionData : questionSet) {
setUI(questionData);
startTimer();
}
private void setUI(Question questionData) {
question.setText(questionData.getQuestion());
ch1.setText(questionData.getC1());
ch2.setText(questionData.getC2());
ch3.setText(questionData.getC3());
}
private void startTimer(){
int interval = 10000;
countDownTimer = new CountDownTimer(interval, 1000) {
public void onTick(long millisUntilFinished) {
time.setText("seconds remaining: "
+ millisUntilFinished / 1000);
}
public void onFinish() {
time.setText("done!");
countDownTimer.cancel();
}
}.start();
}
Here questionSet has two index.
Thanks in advance.
Finally got a solution.
for (final Question questionData : questionSet) {
tempQuestionSet.add(questionData);
setUI(questionData);
startTimer();
break;
}
private void setUI(Question questionData) {
question.setText(questionData.getQuestion());
ch1.setText(questionData.getC1());
ch2.setText(questionData.getC2());
ch3.setText(questionData.getC3());
}
private void startTimer(){
int interval = 10000;
countDownTimer = new CountDownTimer(interval, 1000) {
public void onTick(long millisUntilFinished) {
time.setText("seconds remaining: "
+ millisUntilFinished / 1000);
}
public void onFinish() {
time.setText("done!");
final Question question = getQuestionSet();
if(question == null){
countDownTimer.cancel();
}else{
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
setUI(question);
}
});
countDownTimer.start();
}
}
}.start();
}
private Question getQuestionSet(){
Question newQuestion = null;
for (final Question questionData : questionSet) {
if(tempQuestionSet.contains(questionData)){
}
else{
tempQuestionSet.add(questionData);
return questionData;
}
}
return newQuestion;
}

Categories

Resources