Timer class not restarting timer - Android - java

I have a trivia game of 10 questions with a 10 second timer for each question. When the timer runs out, the question changes to the next but the timer never restarts. It stays at 0. I cannot seem to find where in code that keeps the timer from restarting when the next question is displayed.
Also, code structure suggestions is appreciated!
Thank you in advance.
QuestionView.java
public class QuestionView extends Activity {
int correctAnswers = 0;
int wrongAnswers = 0;
int answer = 0;
int i = 0;
long score = 0;
long startTime = 10000;
long interval = 1000;
long timeElapsed;
boolean timerHasStarted = false;
String category;
Button answer1, answer2, answer3, answer4;
TextView question, timer, timeElapsedView;
ArrayList<Question> queries;
Timer cdTimer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questionviewmain);
answer1 = (Button)findViewById(R.id.answer1);
answer2 = (Button)findViewById(R.id.answer2);
answer3 = (Button)findViewById(R.id.answer3);
answer4 = (Button)findViewById(R.id.answer4);
question = (TextView)findViewById(R.id.question);
category = getIntent().getStringExtra("category");
queries = getIntent().getParcelableArrayListExtra("queries");
timer = (TextView)findViewById(R.id.timer);
timeElapsedView = (TextView)findViewById(R.id.timeElapsedView);
cdTimer = new Timer(startTime, interval);
loadQuestion();
}
public void loadQuestion() {
if(i == 9) {
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.cancel();
timerHasStarted = false;
}
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(0);
if(answer == 0) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
//Same code for button 1 for buttons 2 through 4.
}
}
public void nextQuestion() {
score = score + ((startTime / 100) - timeElapsed);
i++;
loadQuestion();
}
public class Timer extends CountDownTimer {
public Timer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
if(i == 9) {
cdTimer.cancel();
} else {
wrongAnswers++;
nextQuestion();
}
}
#Override
public void onTick(long millisUntilFinished) {
timer.setText("Time remaining: " + (millisUntilFinished / 100));
timeElapsed = 100 - ((startTime - millisUntilFinished) / 100);
timeElapsedView.setText("Points remaining: " + timeElapsed);
}
}
public void endQuiz() {
Intent intent = new Intent(QuestionView.this, Results.class);
intent.putExtra("correctAnswers", correctAnswers);
intent.putExtra("wrongAnswers", wrongAnswers);
intent.putExtra("score", score);
intent.putParcelableArrayListExtra("queries", queries);
intent.putExtra("category", category);
startActivity(intent);
}
}

try the following and see if it helps. furthermore, calling cancel() inside the timer's own onFinish() method is unneeded since the timer would have already been cancelled to reach that method.
public void loadQuestion() {
if(i == 9) {
endQuiz();
} else {
cdTimer.start(); //start timer here
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
cdTimer.cancel(); // end it when clicked.
queries.get(i).setSelectedAnswer(0);
if(answer == 0) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
//Same code for button 1 for buttons 2 through 4.
}
}

Related

MediaPlayer - handler.getCurrentPosition()

The issue is with these lines
seekBar1.setProgress(player.getCurrentPosition());
and
seekBar2.setProgress(player2.getCurrentPosition());
Error
Attempt to invoke virtual method 'int android.media.MediaPlayer.getCurrentPosition()' on a null object reference
also, a small request I have an issue with the handler.postDelayed can you please check this user question too I have the same issue, here is the link to that question
Code // full code is belove this
public class UpdateSeekBar1 implements Runnable {
#Override
public void run() {
currentTime1.setText(createTimerLable1(seekBar1.getProgress()));
seekBar1.setProgress(player.getCurrentPosition());
handler1.postDelayed(this, 100);
}
}
public class UpdateSeekBar2 implements Runnable {
#Override
public void run() {
currentTime2.setText(createTimerLable2(seekBar2.getProgress()));
seekBar2.setProgress(player2.getCurrentPosition());
handler2.postDelayed(this, 100);
}
}
Full Code // the code can be a little confusing and written badly
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MediaPlayer player, player2;
SeekBar seekBar1, seekBar2;
TextView currentTime1, currentTime2;
TextView totalTime1, totalTime2;
Handler handler1 = new Handler();
Handler handler2 = new Handler();
ImageView play, pause, stop, play2, pause2, stop2;
int pauseCurrentPosition, pauseCurrentPosition2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
player = MediaPlayer.create(this, R.raw.dog_howl);
player2 = MediaPlayer.create(this, R.raw.dog_bark);
seekBar1 = findViewById(R.id.seekbar1);
seekBar2 = findViewById(R.id.seekbar2);
play = findViewById(R.id.playbtn);
pause = findViewById(R.id.pausebtn);
stop = findViewById(R.id.stopbtn);
play2 = findViewById(R.id.playbtn2);
pause2 = findViewById(R.id.pausebtn2);
stop2 = findViewById(R.id.stopbtn2);
currentTime1 = findViewById(R.id.currentTime1);
currentTime2 = findViewById(R.id.currentTime2);
totalTime1 = findViewById(R.id.totalTime1);
totalTime2 = findViewById(R.id.totalTime2);
play.setOnClickListener(this);
pause.setOnClickListener(this);
stop.setOnClickListener(this);
play2.setOnClickListener(this);
pause2.setOnClickListener(this);
stop2.setOnClickListener(this);
seekBar1.setMax(player.getDuration());
seekBar2.setMax(player2.getDuration());
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
player.seekTo(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
player2.seekTo(i);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
String totTime1 = createTimerLable1(player.getDuration());
totalTime1.setText(totTime1);
String totTime2 = createTimerLable2(player2.getDuration());
totalTime1.setText(totTime2);
}
#SuppressLint("NonConstantResourceId")
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.playbtn:
UpdateSeekBar1 updateSeekBar1 = new UpdateSeekBar1();
handler1.post(updateSeekBar1);
if (player == null) {
player = MediaPlayer.create(getApplicationContext(), R.raw.dog_howl);
player.start();
} else if (!player.isPlaying()) {
player.seekTo(pauseCurrentPosition);
player.start();
}
break;
case R.id.pausebtn:
if (player != null) {
player.pause();
pauseCurrentPosition = player.getCurrentPosition();
}
break;
case R.id.stopbtn:
if (player != null) {
player.stop();
player = null;
}
break;
case R.id.playbtn2:
UpdateSeekBar2 updateSeekBar2 = new UpdateSeekBar2();
handler2.post(updateSeekBar2);
if (player2 == null) {
player2 = MediaPlayer.create(getApplicationContext(), R.raw.dog_bark);
player2.start();
} else if (!player2.isPlaying()) {
player2.seekTo(pauseCurrentPosition2);
player2.start();
}
break;
case R.id.pausebtn2:
if (player2 != null) {
player2.pause();
pauseCurrentPosition2 = player2.getCurrentPosition();
}
break;
case R.id.stopbtn2:
if (player2 != null) {
player2.stop();
player2 = null;
}
break;
}
}
public String createTimerLable1(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public String createTimerLable2(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public class UpdateSeekBar1 implements Runnable {
#Override
public void run() {
currentTime1.setText(createTimerLable1(seekBar1.getProgress()));
seekBar1.setProgress(player.getCurrentPosition());
handler1.postDelayed(this, 100);
}
}
public class UpdateSeekBar2 implements Runnable {
#Override
public void run() {
currentTime2.setText(createTimerLable2(seekBar2.getProgress()));
seekBar2.setProgress(player2.getCurrentPosition());
handler2.postDelayed(this, 100);
}
}
}
Enter this code:-
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MediaPlayer player, player2;
SeekBar seekBar1, seekBar2;
TextView currentTime1, currentTime2;
TextView totalTime1, totalTime2;
Handler handler1 = new Handler();
Handler handler2 = new Handler();
ImageView play, pause, stop, play2, pause2, stop2;
int pauseCurrentPosition, pauseCurrentPosition2;
UpdateSeekBar1 updateSeekBar1 = new UpdateSeekBar1();
UpdateSeekBar2 updateSeekBar2 = new UpdateSeekBar2();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
player = MediaPlayer.create(this, R.raw.bekhayali);
player2 = MediaPlayer.create(this, R.raw.hawabanke);
seekBar1 = findViewById(R.id.seekbar1);
seekBar2 = findViewById(R.id.seekbar2);
play = findViewById(R.id.playbtn);
pause = findViewById(R.id.pausebtn);
stop = findViewById(R.id.stopbtn);
play2 = findViewById(R.id.playbtn2);
pause2 = findViewById(R.id.pausebtn2);
stop2 = findViewById(R.id.stopbtn2);
currentTime1 = findViewById(R.id.currentTime1);
currentTime2 = findViewById(R.id.currentTime2);
totalTime1 = findViewById(R.id.totalTime1);
totalTime2 = findViewById(R.id.totalTime2);
play.setOnClickListener(this);
pause.setOnClickListener(this);
stop.setOnClickListener(this);
play2.setOnClickListener(this);
pause2.setOnClickListener(this);
stop2.setOnClickListener(this);
seekBar1.setMax(player.getDuration());
seekBar2.setMax(player2.getDuration());
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.seekTo(seekBar.getProgress());
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player2.seekTo(seekBar.getProgress());
}
});
String totTime1 = createTimerLable1(player.getDuration());
totalTime1.setText(totTime1);
String totTime2 = createTimerLable2(player2.getDuration());
totalTime1.setText(totTime2);
}
#SuppressLint("NonConstantResourceId")
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.playbtn:
handler1.post(updateSeekBar1);
if (player == null) {
player = MediaPlayer.create(getApplicationContext(), R.raw.bekhayali);
player.start();
} else if (!player.isPlaying()) {
player.seekTo(pauseCurrentPosition);
player.start();
}
break;
case R.id.pausebtn:
if (player != null) {
player.pause();
pauseCurrentPosition = player.getCurrentPosition();
}
break;
case R.id.stopbtn:
if (player != null) {
player.stop();
handler1.removeCallbacks(updateSeekBar1);
player = null;
}
break;
case R.id.playbtn2:
handler2.post(updateSeekBar2);
if (player2 == null) {
player2 = MediaPlayer.create(getApplicationContext(), R.raw.hawabanke);
player2.start();
} else if (!player2.isPlaying()) {
player2.seekTo(pauseCurrentPosition2);
player2.start();
}
break;
case R.id.pausebtn2:
if (player2 != null) {
player2.pause();
pauseCurrentPosition2 = player2.getCurrentPosition();
}
break;
case R.id.stopbtn2:
if (player2 != null) {
player2.stop();
handler2.removeCallbacks(updateSeekBar2);
player2 = null;
}
break;
}
}
public String createTimerLable1(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public String createTimerLable2(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public class UpdateSeekBar1 implements Runnable {
#Override
public void run() {
currentTime1.setText(createTimerLable1(seekBar1.getProgress()));
seekBar1.setProgress(player.getCurrentPosition());
handler1.postDelayed(this, 100);
}
}
public class UpdateSeekBar2 implements Runnable {
#Override
public void run() {
currentTime2.setText(createTimerLable2(seekBar2.getProgress()));
seekBar2.setProgress(player2.getCurrentPosition());
handler2.postDelayed(this, 100);
}
}}

How can I let my Timer Count when I change the activity to keep counting the time in Android Studio?

I going to fix the issue about when I click the to go another activity and my timer started before, when I back to the timer count activity, the timer stopped and auto reset to 0. How can I manage the activity when I back to timer activity and keep the timer counting?
Here are my code of my timer counter.
// TimerCount
TextView txtvTimer;
Button pauseStartBtn;
Button stopFinishBtn;
boolean timerStarted = false;
Timer timer;
TimerTask timerTask;
Double time = 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer_count);
Log.d(TAG_LIFECYCLE, "In the activity_timer_count onCreate() event");
// timer
txtvTimer = (TextView) findViewById(R.id.txtvTimer);
pauseStartBtn = (Button) findViewById(R.id.btnStartPause);
stopFinishBtn = (Button) findViewById(R.id.btnStopFinish);
stopFinishBtn.setEnabled(false);
timer = new Timer();
// bottom nav
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav);
bottomNavigationView.setSelectedItemId(R.id.timerCountActivity);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.mainActivity:
startActivity(new Intent(getApplicationContext(),MainActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.mapActivity:
startActivity(new Intent(getApplicationContext(),MapActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.timerCountActivity:
return true;
case R.id.userInfoActivity:
startActivity(new Intent(getApplicationContext(),UserInfoActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.settingActivity:
startActivity(new Intent(getApplicationContext(),SettingActivity.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
}
// timer reset button
public void resetTapped(View v) {
AlertDialog.Builder resetAlert = new AlertDialog.Builder(this);
resetAlert.setTitle("Reset Timer");
resetAlert.setMessage("Reset the timer?");
resetAlert.setPositiveButton("Reset", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (timerTask != null) {
timerTask.cancel();
setButton("START", R.color.green);
time = 0.0;
timerStarted = false;
txtvTimer.setText(formatTime(0,0,0));
}
}
});
resetAlert.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
resetAlert.show();
}
// timer start pause button
public void startPauseTapped(View v) {
if (timerStarted == false){
timerStarted = true;
setButton("PAUSE", R.color.red);
startTimer();
onStartClicked(v);
onLocateClicked(v);
stopToPushData(v);
} else {
timerStarted = false;
setButton("Resume", R.color.green);
timerTask.cancel();
onStartClicked(v);
onLocateClicked(v);
}
}
private void setButton(String start, int color) {
pauseStartBtn.setText(start);
pauseStartBtn.setTextColor(ContextCompat.getColor(this, color));
}
private void startTimer() {
timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
time++;
txtvTimer.setText(getTimerText());
}
});
}
};
timer.scheduleAtFixedRate(timerTask,0,1000);
}
private String getTimerText() {
int rounded = (int) Math.round(time);
int seconds = ((rounded % 86400) % 3600) % 60;
int minutes = ((rounded % 86400) % 3600) / 60;
int hours = ((rounded % 86400) / 3600) ;
return formatTime (seconds, minutes, hours);
}
private String formatTime(int seconds, int minutes, int hours) {
return String.format("%02d",hours) + " : " + String.format("%02d",minutes) + " : " + String.format("%02d",seconds);
}
Second, how can I get the timer to calculate the time per second?
Is it rounded % 86400 will be the real second I have counted?
I think it's better to use chronometer
Xml :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<Chronometer
android:id="#+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Main Acitvity:
public class MainActivity extends AppCompatActivity {
Chronometer chronometer ;
long stopTime ; // this variable will count the time when stop counting (when you have left the activity)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chronometer = (Chronometer) findViewById(R.id.chronometer);
}
void StartCounting() {
chronometer.setBase(SystemClock.elapsedRealtime()-stopTime); // This line will set the time to correct when you return to the activity
chronometer.start();
}
void PauseCounting() {
stopTime = SystemClock.elapsedRealtime()-chronometer.getBase();
chronometer.stop();
}
}

CountDownTimer is not stopping on BackPressed running in background,may be handler.postDelayed() is the issue. How to fix it in this code?

My Countdown timer is working fine but when I use back press during running state of the time, my countdown timer did not stop. I have tried everything as follows but none of them is able to stop the countdown timer from running in the background. After searching the forum an applying the results from it to my project I am unable to figure out whats fault in my code. Please anyone help me out and I shall be very thankful.
public class QuizActivity extends AppCompatActivity {
private static final long COUNTDOWN_IN_MILLIS = 30000 ;
List<Questions> mQuestions;
int score = 0;
int qid = 0;
Questions currentQ;
TextView txtQuestions, textViewCountDown;
RadioButton rda, rdb, rdc;
Button btnNext;
private QuestionsViewModel questionsViewModel;
private RelativeLayout relativeLayout;
private LinearLayout linearLayout;
private ColorStateList textColorDefaultCd;
private CountDownTimer countDownTimer;
private long timeLeftInMillis;
private Handler handler;
private Runnable runnable = new Runnable() {
#Override
public void run() {
takeAction();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
textViewCountDown = findViewById(R.id.text_view_countdown);
relativeLayout = (RelativeLayout)findViewById(R.id.profileLoadingScreen);
linearLayout = (LinearLayout) findViewById(R.id.linearView);
textColorDefaultCd = textViewCountDown.getTextColors();
fetchQuestions();
questionsViewModel = ViewModelProviders.of(QuizActivity.this).get(QuestionsViewModel.class);
questionsViewModel.getAllQuestions().observe(this, new Observer<List<Questions>>() {
#Override
public void onChanged(#Nullable final List<Questions> words) {
// Update the cached copy of the words in the adapter.
mQuestions = words;
//Collections.shuffle(mQuestions);
Collections.addAll(mQuestions);
}
});
}
private void fetchQuestions() {
DataServiceGenerator dataServiceGenerator = new DataServiceGenerator();
Service service = DataServiceGenerator.createService(Service.class);
Call<List<QuestionsModel>> call = service.getQuestions();
call.enqueue(new Callback<List<QuestionsModel>>() {
#Override
public void onResponse(Call<List<QuestionsModel>> call, Response<List<QuestionsModel>> response) {
if (response.isSuccessful()){
if (response != null){
List<QuestionsModel> questionsModelList = response.body();
for (int i = 0; i < questionsModelList.size(); i++){
String question = questionsModelList.get(i).getQuestion();
String answer = questionsModelList.get(i).getAnswer();
String opta = questionsModelList.get(i).getOpta();
String optb = questionsModelList.get(i).getOptb();
String optc = questionsModelList.get(i).getOptc();
Questions questions = new Questions(question, answer, opta, optb, optc);
questionsViewModel.insert(questions);
}
handler = new Handler();//add this
handler.postDelayed(runnable,3000);
/* Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
takeAction();
}
}, 3000); */
}
}else{
}
}
#Override
public void onFailure(Call<List<QuestionsModel>> call, Throwable t) {
}
});
}
private void setQuestionView()
{
txtQuestions.setText(currentQ.getQuestion());
rda.setText(currentQ.getOptA());
rdb.setText(currentQ.getOptB());
rdc.setText(currentQ.getOptC());
qid++;
}
private void startCountDown() {
countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
timeLeftInMillis = 0;
updateCountDownText();
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}.start();
}
private void updateCountDownText() {
int minutes = (int) (timeLeftInMillis / 1000) / 60;
int seconds = (int) (timeLeftInMillis / 1000) % 60;
String timeFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
textViewCountDown.setText(timeFormatted);
if (timeLeftInMillis < 10000) {
textViewCountDown.setTextColor(Color.RED);
} else {
textViewCountDown.setTextColor(textColorDefaultCd);
}
}
private void takeAction() {
relativeLayout.setVisibility(View.GONE);
linearLayout.setVisibility(View.VISIBLE);
textViewCountDown.setVisibility(View.VISIBLE);
timeLeftInMillis = COUNTDOWN_IN_MILLIS;
startCountDown();
currentQ = mQuestions.get(qid);
txtQuestions = (TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radio0);
rdb=(RadioButton)findViewById(R.id.radio1);
rdc=(RadioButton)findViewById(R.id.radio2);
btnNext=(Button)findViewById(R.id.button1);
setQuestionView();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
if (grp.getCheckedRadioButtonId() == -1){
Toast.makeText(getApplicationContext(),
"Please Select an Answer",
Toast.LENGTH_SHORT)
.show();
return;
}else{
// countDownTimer.cancel();
}
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
grp.clearCheck();
//Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getAnswer().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}else{
}
if(qid<10){
currentQ=mQuestions.get(qid);
setQuestionView();
}else{
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer != null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onPause() {
super.onPause();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onStop() {
super.onStop();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
public void onBackPressed() {
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
}
Try this code
#Override
public void onBackPressed() {
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}

CountDownTimer keep running even declared cancel()

public class GameActivity extends AppCompatActivity {
TextView txtTurn, txtScore, txtQuestion, txtQuestionNumber, txtTimer;
Button[] btnAnswers;
Player players[];
ArrayList<Question> questions;
Question currentQuestion;
CountDownTimer gameTime;
Boolean answered, timesup;
int score, turn, round;
final int TIMES = 11000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
txtTurn = (TextView)findViewById(R.id.txtTurnGame);
txtScore = (TextView)findViewById(R.id.txtScoreGame);
txtTimer = (TextView)findViewById(R.id.txtTimer);
txtQuestionNumber = (TextView)findViewById(R.id.questionNumber);
txtQuestion = (TextView)findViewById(R.id.txtQuestion);
btnAnswers = new Button[4];
btnAnswers[0] = (Button)findViewById(R.id.answer1);
btnAnswers[1] = (Button)findViewById(R.id.answer2);
btnAnswers[2] = (Button)findViewById(R.id.answer3);
btnAnswers[3] = (Button)findViewById(R.id.answer4);
answered = false;
timesup = false;
Intent intent = getIntent();
players = MainActivity.players;
turn = intent.getExtras().getInt("turn");
score = players[turn].getScore();
round = intent.getExtras().getInt("round");
questions = MainActivity.shuffledQuestionList;
currentQuestion = questions.get(round/2);
Integer[] randomAnswer = new Integer[4];
for (int i = 0; i < randomAnswer.length; i++) {
randomAnswer[i] = i;
}
Collections.shuffle(Arrays.asList(randomAnswer));
txtTurn.setText(TurnActivity.txtTurn1.getText());
txtScore.setText("Score : " + Integer.toString(score));
txtQuestion.setText(currentQuestion.getQuestion());
txtQuestionNumber.setText("QUESTION #" + Integer.toString(round/2+1));
for (int i = 0; i < randomAnswer.length; i++){
String[] answers = currentQuestion.getAnswersList();
btnAnswers[i].setText(answers[randomAnswer[i]]);
}
gameTime = new CountDownTimer(TIMES, 1000){
public void onTick(long millisUntilFinished) {
if(!timesup)
txtTimer.setText("Time : " + millisUntilFinished / 1000 + "s");
}
public void onFinish() {
txtTimer.setText("Time's Up");
timesup = true;
finishTurn();
}
};
gameTime.start();
}
public void answerChoose(View v){
if(!answered && !timesup){
answered = true;
gameTime.cancel();
Button btnPressed = ((Button) v);
if(btnPressed.getText().equals(currentQuestion.getAnswer())){
btnPressed.setBackgroundColor(Color.GREEN);
players[turn].setScore(score+1);
}
else{
btnPressed.setBackgroundColor(Color.RED);
}
finishTurn();
}
}
private void finishTurn(){
gameTime.cancel();
if(round+1 >= 10){
final Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
startActivity(intent);
finish();
}
else {
final Intent intent = new Intent(getApplicationContext(), TurnActivity.class);
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//Toast.makeText(getApplicationContext(), "Player2 Time!", Toast.LENGTH_SHORT).show();
intent.putExtra("turn", turn);
intent.putExtra("round", round + 1);
startActivity(intent);
finish();
}
}.start();
}
}
So, I try to make a quiz game. There are 4 buttons as answer choices. When user click a(any) button, it refer to answerChoose method which stops the timer and make an intent to TurnActivity (finishTurn method). The timer displayed as a TextView and of course it stopped, the TextView not changed anymore (seems like the timer stopped)
public void answerChoose(View v){
if(!answered && !timesup){
answered = true;
gameTime.cancel();
Button btnPressed = ((Button) v);
//Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
if(btnPressed.getText().equals(currentQuestion.getAnswer())){
btnPressed.setBackgroundColor(Color.GREEN);
players[turn].setScore(score+1);
}
else{
btnPressed.setBackgroundColor(Color.RED);
}
finishTurn();
}
}
But something happen really weird, after reached the TurnActivity, the timer doesn't seem to stop, the timer keeps running until reach the end and make a new intent to TurnActivity (once again). As you can see I called finishTurn method in onFinish method of CountDownTimer. So, the timer itself not stopped even the cancel method declared in answerChoose method.
gameTime = new CountDownTimer(TIMES, 1000){
public void onTick(long millisUntilFinished) {
if(!timesup)
txtTimer.setText("Time : " + millisUntilFinished / 1000 + "s");
}
public void onFinish() {
txtTimer.setText("Time's Up");
timesup = true;
finishTurn();
}
};
Problem solved. All I have to do is override the onStop method.
#Override
protected void onStop() {
super.onStop();
gameTime.cancel();
}

ProgressBar with a countdowntimer - Android

I have a 20 second countdown timer successfully working on my trivia game. I want to add a ProgressBar (not a ProgressDialog) to the screen. I found the developer guide for Android confusing. I googled lots of examples and tried to combine them into my code. Right now all that displays when I run a game is an empty bar with no "progress" made during each question of the game.
QuestionView.java
public class QuestionView extends Activity {
int correctAnswers = 0;
int wrongAnswers = 0;
int answer = 0;
int i = 0;
long score = 0;
long startTime = 20000;
long interval = 1000;
long points;
boolean timerHasStarted = false;
String category;
Button answer1, answer2, answer3, answer4;
TextView question, pointCounter, questionNumber, timeCounter;
ArrayList<Question> queries;
Timer cdTimer;
ProgressBar bar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questionviewmain);
answer1 = (Button)findViewById(R.id.answer1);
answer2 = (Button)findViewById(R.id.answer2);
answer3 = (Button)findViewById(R.id.answer3);
answer4 = (Button)findViewById(R.id.answer4);
question = (TextView)findViewById(R.id.question);
category = getIntent().getStringExtra("category");
queries = getIntent().getParcelableArrayListExtra("queries");
pointCounter = (TextView)findViewById(R.id.timer);
questionNumber = (TextView)findViewById(R.id.timeElapsedView);
timeCounter = (TextView)findViewById(R.id.timeCounter);
cdTimer = new Timer(startTime, interval);
bar = (ProgressBar)findViewById(R.id.progressbar);
bar.setIndeterminate(false);
bar.setMax(9);
loadQuestion();
}
public void loadQuestion() {
bar.setProgress(i);
if(i == 10) {
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.start();
timerHasStarted = false;
}
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(0);
if(answer == 0) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
answer2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(1);
if(answer == 1) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
answer3.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(2);
if(answer == 2) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
answer4.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(3);
if(answer == 3) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
}
}
public ArrayList<Question> getQueries() {
return queries;
}
public void nextQuestion() {
score = score + points;
i++;
loadQuestion();
}
public class Timer extends CountDownTimer {
public void startCountdownTimer() {
}
public Timer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
if(i >= 9) {
cdTimer.cancel();
endQuiz();
} else {
wrongAnswers++;
nextQuestion();
}
}
#Override
public void onTick(long millisUntilFinished) {
timeCounter.setText("Time remaining: " + (millisUntilFinished / 100));
points = (millisUntilFinished / 100) / 2;
pointCounter.setText("Points remaining: " + points);
if(i < 10) {
questionNumber.setText("Question " + (i + 1) + " of 10");
}
}
}
public void endQuiz() {
Intent intent = new Intent(QuestionView.this, Results.class);
intent.putExtra("correctAnswers", correctAnswers);
intent.putExtra("wrongAnswers", wrongAnswers);
intent.putExtra("score", score);
intent.putParcelableArrayListExtra("queries", queries);
intent.putExtra("category", category);
startActivity(intent);
}
}
XML code
<ProgressBar
android:id="#+id/progressbar"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:visibility="visible"
style="#android:style/Widget.ProgressBar.Horizontal" />
What I am looking for is for the ProgressBar to slowly tick down until the 20 seconds the user is allotted for each question is gone.
New Answer
To do this let's add a new line to onTick():
bar.setProgress((int) Math.round(millisUntilFinished / 1000.0));
(You may need to tweak the data types, I am away from my compiler... Also I don't like the CountDownTimer class, it is inaccurate and often skips the second to last number. I wrote an alternate class here: android CountDownTimer - additional milliseconds delay between ticks)
Original Answer
I have a couple pointers:
Have you defined a maximum value for your ProgressBar?
bar.setMax(9);
I suggest loading i as the progress instead of the constant value of 10:
bar.setProgress(i);
If you still do not see any progress ensure that you are not in indeterminate mode:
bar.setIndeterminate(false);
(This assume that you are using a ProgressBar that can depict progress.)
Addition
Move this code into onCreate():
bar = (ProgressBar)findViewById(R.id.progressbar);
bar.setIndeterminate(false); // May not be necessary
bar.setMax(9);
Then move this line to loadQuestion():
bar.setProgress(i);
Otherwise the progress will never be updated since you only create one CountDownTimer and you never actually call startCountdownTimer().

Categories

Resources