Keep the CountDownTimer running after orientation change - java

I have made a CountDownTimer that works perfectly - you can get the correct time for soft/medium/hard-boiling an egg. My problem is that the timer resets after orientation change. I have googled and tried so many solution, still I don't understand how to use the onSave and onRestore properly. Here's my code:
Any tips?
package com.dohman.boilaneggbae;
import android.graphics.PorterDuff;
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 java.util.Locale;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
private static final String CURRENT_TIME = "currentTime";
private static final String DURATION_TIME = "durationTime";
private long currentTime;
private int durationTime;
private TextView time;
private Button buttonLargeSize;
private Button buttonMediumSize;
private Button buttonSoft;
private Button buttonMedium;
private Button buttonHard;
private Button buttonHellaHard;
private CountDownTimer countDownTimer;
private EggSize mediumOrLarge = EggSize.UNDEFINED;
private boolean alreadyRunning = false;
enum EggSize {
UNDEFINED, MEDIUM, LARGE;
}
private View.OnClickListener btnMediumSizeClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
mediumOrLarge = EggSize.MEDIUM;
}
};
private View.OnClickListener btnLargeSizeClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
mediumOrLarge = EggSize.LARGE;
}
};
private View.OnClickListener btnSoftClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
if ((mediumOrLarge != EggSize.UNDEFINED) && (alreadyRunning == false)) {
alreadyRunning = true;
durationTime = 240;
start(240);
} else if (mediumOrLarge == EggSize.UNDEFINED) {
time.setText("Choose size first");
} else {
alreadyRunning = false;
cancel();
}
}
};
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putLong(CURRENT_TIME, currentTime);
savedInstanceState.putInt(DURATION_TIME, durationTime);
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
currentTime = savedInstanceState.getLong(CURRENT_TIME);
durationTime = savedInstanceState.getInt(DURATION_TIME);
}
time = findViewById(R.id.time);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
currentTime = savedInstanceState.getLong(CURRENT_TIME);
durationTime = savedInstanceState.getInt(DURATION_TIME);
currentTime -= durationTime;
}
private void start(int duration) {
time.setText("");
if (mediumOrLarge == EggSize.MEDIUM) {
duration -= 60;
}
countDownTimer = new CountDownTimer(duration * 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
String text = String.format(Locale.getDefault(), "%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60);
time.setText(text);
}
countDownTimer.start();
}
}

I finally solved this! Using this link:
https://codinginflow.com/code-examples/android/countdown-timer/part-2
Those are the codes:
package com.codinginflow.countdowntimerexample;
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 java.util.Locale;
public class MainActivity extends AppCompatActivity {
private static final long START_TIME_IN_MILLIS = 600000;
private TextView mTextViewCountDown;
private Button mButtonStartPause;
private Button mButtonReset;
private CountDownTimer mCountDownTimer;
private boolean mTimerRunning;
private long mTimeLeftInMillis = START_TIME_IN_MILLIS;
private long mEndTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextViewCountDown = findViewById(R.id.text_view_countdown);
mButtonStartPause = findViewById(R.id.button_start_pause);
mButtonReset = findViewById(R.id.button_reset);
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();
}
});
updateCountDownText();
}
private void startTimer() {
mEndTime = System.currentTimeMillis() + mTimeLeftInMillis;
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
mTimerRunning = false;
updateButtons();
}
}.start();
mTimerRunning = true;
updateButtons();
}
private void pauseTimer() {
mCountDownTimer.cancel();
mTimerRunning = false;
updateButtons();
}
private void resetTimer() {
mTimeLeftInMillis = START_TIME_IN_MILLIS;
updateCountDownText();
updateButtons();
}
private void updateCountDownText() {
int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
mTextViewCountDown.setText(timeLeftFormatted);
}
private void updateButtons() {
if (mTimerRunning) {
mButtonReset.setVisibility(View.INVISIBLE);
mButtonStartPause.setText("Pause");
} else {
mButtonStartPause.setText("Start");
if (mTimeLeftInMillis < 1000) {
mButtonStartPause.setVisibility(View.INVISIBLE);
} else {
mButtonStartPause.setVisibility(View.VISIBLE);
}
if (mTimeLeftInMillis < START_TIME_IN_MILLIS) {
mButtonReset.setVisibility(View.VISIBLE);
} else {
mButtonReset.setVisibility(View.INVISIBLE);
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong("millisLeft", mTimeLeftInMillis);
outState.putBoolean("timerRunning", mTimerRunning);
outState.putLong("endTime", mEndTime);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mTimeLeftInMillis = savedInstanceState.getLong("millisLeft");
mTimerRunning = savedInstanceState.getBoolean("timerRunning");
updateCountDownText();
updateButtons();
if (mTimerRunning) {
mEndTime = savedInstanceState.getLong("endTime");
mTimeLeftInMillis = mEndTime - System.currentTimeMillis();
startTimer();
}
}
}
EDIT: For some reason I can't mark my own answer as a solution, but this problem is solved anyway. (Answered)

Related

Cannot resolve too many methods

This is for my school project and yup I'm still new at android programming. I have no idea about why these error messages keep showing up.
The error messages is:
a. cannot resolve method 'onCreate(savedInstanceState)' on the part after 'Super'
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workouttimer);
b. cannot resolve method 'findViewById(int)'
mTextViewCountDown = findViewById(R.id.text_view_countdown);
mButtonStartPause = findViewById(R.id.button_start_pause);
mButtonReset = findViewById(R.id.button_reset);
c. cannot resolve method 'onSaveInstanceState(android.os.Bundle)'
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong("millisLeft", mTimeLeftInMillis);
outState.putBoolean("timerRunning", mTimerRunning);
outState.putLong("endTime", mEndTime);
}
d. cannot resolve method 'onRestoreInstanceState(android.os.Bundle)'
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mTimeLeftInMillis = savedInstanceState.getLong("millisLeft");
mTimerRunning = savedInstanceState.getBoolean("timerRunning");
updateCountDownText();
updateButtons();
This is my timer.java (actually this is my second mainactivity java because my application is multi-activity)
package com.example.lenovo.pomodorotest;
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 java.util.Locale;
public class timer {
private static final long START_TIME_IN_MILLIS = 600000;
private TextView mTextViewCountDown;
private Button mButtonStartPause;
private Button mButtonReset;
private CountDownTimer mCountDownTimer;
private boolean mTimerRunning;
private long mTimeLeftInMillis = START_TIME_IN_MILLIS;
private long mEndTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workouttimer);
mTextViewCountDown = findViewById(R.id.text_view_countdown);
mButtonStartPause = findViewById(R.id.button_start_pause);
mButtonReset = findViewById(R.id.button_reset);
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();
}
});
updateCountDownText();
}
private void setContentView(int workouttimer) {
}
private void startTimer() {
mEndTime = System.currentTimeMillis() + mTimeLeftInMillis;
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
mTimerRunning = false;
updateButtons();
}
}.start();
mTimerRunning = true;
updateButtons();
}
private void pauseTimer() {
mCountDownTimer.cancel();
mTimerRunning = false;
updateButtons();
}
private void resetTimer() {
mTimeLeftInMillis = START_TIME_IN_MILLIS;
updateCountDownText();
updateButtons();
}
private void updateCountDownText() {
int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
mTextViewCountDown.setText(timeLeftFormatted);
}
private void updateButtons() {
if (mTimerRunning) {
mButtonReset.setVisibility(View.INVISIBLE);
mButtonStartPause.setText("Pause");
} else {
mButtonStartPause.setText("Start");
if (mTimeLeftInMillis < 1000) {
mButtonStartPause.setVisibility(View.INVISIBLE);
} else {
mButtonStartPause.setVisibility(View.VISIBLE);
}
if (mTimeLeftInMillis < START_TIME_IN_MILLIS) {
mButtonReset.setVisibility(View.VISIBLE);
} else {
mButtonReset.setVisibility(View.INVISIBLE);
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong("millisLeft", mTimeLeftInMillis);
outState.putBoolean("timerRunning", mTimerRunning);
outState.putLong("endTime", mEndTime);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mTimeLeftInMillis = savedInstanceState.getLong("millisLeft");
mTimerRunning = savedInstanceState.getBoolean("timerRunning");
updateCountDownText();
updateButtons();
if (mTimerRunning) {
mEndTime = savedInstanceState.getLong("endTime");
mTimeLeftInMillis = mEndTime - System.currentTimeMillis();
startTimer();
}
}
}
}
This is my workouttimer.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text_view_countdown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="00:00"
android:textColor="#android:color/black"
android:textSize="60sp" />
<Button
android:id="#+id/button_start_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text_view_countdown"
android:layout_centerHorizontal="true"
android:text="Studying!" />
<Button
android:id="#+id/button_start_letsgetrest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button_start_pause"
android:layout_centerHorizontal="true"
android:text="Lets Get Rest!" />
<Button
android:id="#+id/button_reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text_view_countdown"
android:layout_marginStart="11dp"
android:layout_toEndOf="#+id/button_start_pause"
android:text="reset"
android:visibility="invisible"
xmlns:tools="http://schemas.android.com/tools":visibility="visible"
android:layout_marginLeft="11dp"
android:layout_toRightOf="#+id/button_start_pause" />
</RelativeLayout>
any help would be appreciated. Thanks
Change your timer.java file to this and then rebuild
public class timer extends AppCompatActivity {
All of the methods that you are overriding is from the class AppCompatActivity or Activity.Hence, to use these methods in your class, you will have to extend the classes AppCompatActivity or Activity like -
public class timer extends AppCompatActivity{
//Your code
}
Note - Please, while creating classes, start it with a capital letter as per convention.

How do I access my CountDownTimer to cancel it in Java?

Making a small game in Android Studio. Basically, the user will have a set amount of time to trigger a button press or the game will end. My CountDownTimer object is inside of a different function than my button click handler. How can I cancel the countDownTimer using cancel() from the button click handler.
Here is my code:
public countDownTimer timeLimit;
public void generate() {
final ProgressBar timer = (ProgressBar)findViewById(R.id.timer);`
int timeoutSeconds = 5000;
timer.setMax(timeoutSeconds);
timeLimit = new CountDownTimer(timeoutSeconds, 100) {
public void onTick(long millisUntilFinished) {
int timeUntilFinished = (int) millisUntilFinished;
timer.setProgress(timeUntilFinished);
}
public void onFinish() {
gameOver();
}
};
timeLimit.start();
}
public void buttonClicked(View v) {
timeLimit.cancel();
}
I'd be happy to hear any alternative ways to do this as well.
The code below works perfectly for me.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ProgressBar progressBar;
private CountDownTimer countDownTimer;
private Button stopTimerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
stopTimerButton = (Button)findViewById(R.id.button);
stopTimerButton.setOnClickListener(this);
int timeoutSeconds = 5000;
progressBar.setMax(timeoutSeconds);
countDownTimer = new CountDownTimer(timeoutSeconds,100) {
#Override
public void onTick(long millisUntilFinished) {
int timeUntilFinished = (int) millisUntilFinished;
progressBar.setProgress(timeUntilFinished);
}
#Override
public void onFinish() {
}
};
countDownTimer.start();
}
#Override
public void onClick(View view) {
if(view == stopTimerButton){
countDownTimer.cancel();
}
}
}

Progress bar in quiz (Android Studio)

I am creating a quiz game and I have added progress bar. I want the progress bar to give 10 seconds to answer each question and if the time runs out it should display the results screen. How do I this?
package com.example.sqz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class QuestionActivity extends Activity {
List<Question> quesList;
int score = 0;
int qid = 0;
Question currentQuestion;
TextView txtQuestion, times, scored;
Button Answer1, Answer2, Answer3, Answer4;
QuizHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//level difficulty
int level;
level = getIntent().getIntExtra("level",-1); //get LEVEL from intent. If no LEVEL in intent, LEVEL=-1.
//if level not equal "-1" (so level was in intent), get questions for this level from database
if(level!=-1) {
db=new QuizHelper(this);
quesList=db.getAllQuestionsByLevel(level);
}
currentQuestion = quesList.get(qid); // current question
txtQuestion = (TextView) findViewById(R.id.txtQuestion); // textview to view the question
// the four answer buttons
Answer1 = (Button) findViewById(R.id.btnAnswer1);
Answer2 = (Button) findViewById(R.id.btnAnswer2);
Answer3 = (Button) findViewById(R.id.btnAnswer3);
Answer4 = (Button) findViewById(R.id.btnAnswer4);
// text view to show score
scored = (TextView) findViewById(R.id.score);
// textview for timer
times = (TextView) findViewById(R.id.timers);
// method to set the game
setQuestionView();
times.setText(R.string.timertext);
final ProgressBar mProgressBar;
CountDownTimer mCountDownTimer;
final int[] i = {0};
mProgressBar=(ProgressBar)findViewById(R.id.progressbar);
mProgressBar.setProgress(i[0]);
mCountDownTimer=new CountDownTimer(5000,1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress" + i[0] + millisUntilFinished);
i[0]++;
mProgressBar.setProgress(i[0]);
}
#Override
public void onFinish() {
//Do what you want
i[0]++;
mProgressBar.setProgress(i[0]);
}
};
mCountDownTimer.start();;
// button click listeners
Answer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // method to check if the answer is correct
getAnswer(Answer1.getText().toString());
}
});
Answer2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(Answer2.getText().toString());
}
});
Answer3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(Answer3.getText().toString());
}
});
Answer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(Answer4.getText().toString());
}
});
}
public void getAnswer(String AnswerString) {
if (currentQuestion.getANSWER().equals(AnswerString)) {
score = score + 5; // increase the sore by 5 if the answer is correct
scored.setText("Score : " + score); // set text of textview to score
} else { //load the result screen if wrong answer is selected
Intent intent;
intent = new Intent(QuestionActivity.this,
ResultActivity.class);
Bundle b;
b = new Bundle();
b.putInt("score", score);
intent.putExtras(b); // Put your score to your next
startActivity(intent); // starts the activity
finish();
}
if (qid < 20) { // 20 questions for each level
// until the questions are over do this
currentQuestion = quesList.get(qid);
setQuestionView();
} else {
// once the questions are finished show results screen
Intent intent = new Intent(QuestionActivity.this,
ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
}
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
times.setText("Time is up");
}
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
times.setText(hms);
}
}
private void setQuestionView() {
// the method which will put questions and answers together
txtQuestion.setText(currentQuestion.getQUESTION());
Answer1.setText(currentQuestion.getA1());
Answer2.setText(currentQuestion.getA2());
Answer3.setText(currentQuestion.getA3());
Answer4.setText(currentQuestion.getA4());
qid++;
}
}
You could use a running Thread or AsyncTask
1)For a running Thread,
In your activity xml,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
style="#android:style/Widget.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:progress="100"
android:id="#+id/progress"/>
</LinearLayout>
In your activity
public class TestActivity extends AppCompatActivity{
private ProgressBar moveBar;
private int count;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
moveBar = (ProgressBar)findViewById(R.id.progress);
moveBar.setProgress(100);
startProgress();
}
private void startProgress() {
Thread sleep = new Thread(new Runnable() {
#Override
public void run() {
for(count =10; count >=0; count --) {
try {
Thread.sleep(1000); //every 1sec
// here you check for the result if correct
//i use count == 5 as an example, uncomment to see
/*if(count == 5){
count = 10;
moveBar.setProgress(100);
startProgress();
break;
}*/
}catch (Exception i){
i.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
moveBar.setProgress(10 * count);
Log.e("Count", " " + count);
if(count == 0){
Toast.makeText(getApplicationContext(),
"Result screen", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});sleep.start();
}
}
2) For AsyncTask, use these links to guide you
http://www.compiletimeerror.com/2013/01/why-and-how-to-use-asynctask.html#.Vz7rW3yrS6k
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html
https://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/

Where do i add the timer code in my program ?

This is my top of my code:
public class MainActivity extends ActionBarActivity
{
private static final int MY_DATA_CHECK_CODE = 0;
public static MainActivity currentActivity;
TextToSpeech mTts;
private String targetURL;
private String urlParameters;
private Button btnClick;
private String clicking = "clicked";
private String[] ipaddresses = new String[]{
"http://10.0.0.1:8098/?cmd=nothing",
"http://192.168.1.10:8098/?cmd=nothing"};
private String iptouse = "";
private TextView text;
private boolean connectedtoipsuccess = false;
private int counter = 0;
private NotificationCompat.Builder mbuilder;
private Timer timer = new Timer();
TextView timerTextView;
long startTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
currentActivity = this;
initTTS();
}
And i want to add this code to my program so when i'm running my program i will the timer running.
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.test_activity);
timerTextView = (TextView) findViewById(R.id.timerTextView);
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");
}
What i want it to do is once i'm running the program the timer will start.
But i can't find how and where to add this part of the timer code.
I tried in the onCreate and i tried after the onCreate but it give errors since you can just add #override
You will probably want to set up another class (either in the same class or in its own class) and implement Runnable then from your on create make instance to that runnable.

How to increment countdown timer during runtime?

I am making a course project and for this project, I will need to show a countdown timer. There will be a button which increments the timer by 5+ second. For example if the timer is set and started at 1:00 and if a user clicks the button, the timer must increase +5 like 1:05.
My code:
public class MainActivity extends Activity {
Button incrementTime, startTime;
public TextView timedisplay;
long millisInFuture = 1000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
incrementTime = (Button) findViewById(R.id.button2);
startTime = (Button) findViewById(R.id.button3);
timedisplay = (TextView) findViewById(R.id.mycounter);
resetText();
incrementTime.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
millisInFuture += 1000;
resetText();
}
});
startTime.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
CountDownTimer wavetimer = new myTimer(millisInFuture + 3000, 1000).start();
// ^ add 3 seconds.
}
});}
protected void resetText() {
timedisplay.setText("Time Left: " + millisInFuture / 1000);
}
public class myTimer extends CountDownTimer {
private long millisActual;
public myTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
millisActual = millisInFuture - 3000;
}
#Override
public void onTick(long millisUntilFinished) {
//v start showing the tick after 3 seconds.
if (millisUntilFinished <= millisActual) {
timedisplay.setText("Time Left: " + millisUntilFinished / 1000);
}
}
#Override
public void onFinish() {
timedisplay.setText("Countdown Finished");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
My problem:
This works the same way I want but it only increments after the timer has finished running. I want it to increment during the countdown runtime!
You can use this class for your needs:
public abstract class MyCountDownTimer {
private CountDownTimer cdt;
private long millisInFuture;
private long countDownInterval;
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
this.millisInFuture = millisInFuture;
this.countDownInterval = countDownInterval;
recreateCounter(millisInFuture, countDownInterval);
}
public abstract void onFinish();
public abstract void onTick(long millisUntilFinished);
public void start(){
cdt.start();
}
private void setMillisInFuture(long millisInFuture){
this.millisInFuture = millisInFuture;
}
public void onIncrement(long millis){
millisInFuture += millis;
recreateCounter(millisInFuture, countDownInterval);
}
private void recreateCounter(long millisInFuture, long countDownInterval){
if(cdt != null){
try {
cdt.cancel();
} catch (Exception e) {
}
}
cdt = new CountDownTimer(millisInFuture, countDownInterval) {
#Override
public void onTick(long millisUntilFinished) {
setMillisInFuture(millisUntilFinished);
MyCountDownTimer.this.onTick(millisUntilFinished);
}
#Override
public void onFinish() {
MyCountDownTimer.this.onFinish();
}
};
}
}

Categories