2

I am trying to pause CountDownTimer using Boolean what happen is when i press pause button the tvTimer Stops updating the Time but the countdowntimer continuously counting then when i press the resume button the tvTimer Updates the countdowntimer status on where it is really on like for example countdowntimer starts say 30 29 28 then pause the tvTimer stops at 28 but really the countdown timer is still working then lets say the countdowntimer is in 25 now but the textview is still in 28 right? then i press resume the textview that display the timer update it to 25 where the countdowntimer is i think im just missing a code to stop the countdowntimer.... i have no idea really what it is T_T will u guys help me tho

package org.intercode.lifeatceu;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.util.HashSet;
import java.util.Random;

public class levelone extends AppCompatActivity {
TextView tv1, tvCred, tvQuestion, tvTimer;
Button btNext, btPause ,btResume;
RadioButton rb1, rb2;
RadioGroup rg;
LinearLayout ll;
CountDownTimer timer;

String questions[] =
        {
                "Dr. Ma Cristina D. Padolina is the President and Chief Academic Officer",
                "Mr. Irineo C. Espino is the Vice President for Academic Affairs",
                "Dr. Teresa R. Perez is the Vice President for Administration and Information Officer",
                "Ms. Corazon M. Tiongco is thr Asst. Treasurer and Procurement Dept. Head",
                "Dr. Rhoda C. Aguilar is the University Registrar",
                "Dr. Olivia M. Limuaca is the Vice President of Malolos Campus",
                "Dr. Ma. Flordeliza L. Anastacio is the Vice President of Makati Campus",
                "Dr. Maria Clara Perlita Erna V. Yabut is the Vice President for Research & Evaluation",
                "Dr. Carlito B. Olaer is the Vice President for Student Affairs",
                "Ms. Bernardita T. Traje is the Asst. Comptroller",
                "Mr. Cesar F. Tan is the Treasurer, Asst. Corporate Secretary & Asst. Compliance Officer",
                "Justice Josue N. Bellosillo is the Dean of School of Law and Jurisprudence at CEU MAKATI",
                "Mr. Marcial L. Anacio is the Program head of Computer Science and Information Tech. Department at CEU MAKATI",
                "Atty. Rita Linda V. Jimeno is the Associate Dean of School of Law and Jurisprudence at CEU MAKATI",
                "Dr. Teresita I. Barcelona is the dean of Nursing at CEU MANILA",
                "Dr. Cecilia C. Uncad is the Dean of Optometry at CEU MANILA",
                "Dr. Jessica L. Flor-Torre is the Dean of Nutrition and Hospitality Management at CEU MANILA",
                "Dean Melito S. Salazar, Jr. is the dean of Accountancy and Management at CEU MANILA",
                "Dr. Charito M. Bermido is the dean of Medical Technology at CEU MANILA",
                "Dr. Teresita G. Carey is the Dean of Science and Technology at CEU MANILA",
                "Dr. Julieta Z. Dungca is the Dean of Educational, Liberal, Arts, Music, Social Wok at CEU MANILA",
                "Dr. Pearly P. Lim is the Dean of Pharmacy at CEU MANILA",
                "Dr. Cecilla D, Santiago is the Dean of Dentistry at CEU MANILA",
                "Dr. Milagros L. Borabo is the Director of Professional and Continuing Educational(PACE)",
                "Dr. Ma. Flordeliza L. Anastacio is the Vice President and Dean of Studies at CEU MALOLOS",
                "Dr. Nilo V. Francisco is the Dean of Management and Technology at CEU MALOLOS",
                "Dr. Elizabeth C. Roces is the Dean of Education, Liberal Arts and Science at CEU MALOLOS",
                "Ms. Veronica F. Balintona is the Asst. Dean of Nutrition and Hospitality management at CEU MANILA",
                "Mrs. Elvira L. Urgel is the Asst. Dean of Nursing at CEU MANILA",
                "Dr. Aileen C. Patron is the Asst. Dean of Medical Technology at CEU MANILA",
                "Dr. Juliana M. Laraya is the Asst. Dean of Educational, Liberal Arts, Music, Social Work at CEU MANILA",
                "Mrs. Emma C. Castro is the Administrative Officer (General Services) at CEU MAKITA",
                "Mrs Julie L. Ibe is the Academic Coordinator of Cash Division at CEU MALOLOS",
                "Mrs. Ma. Armela Pamiloza is the Academic Coordinator Level III Nursing at CEU MALOLOS",
                "Mrs. Rosa M. Quizon is the Academic Coordinator of Level II Nursing at CEU MALOLOS",
                "Mrs. Luningning O. Marcelino is the Academic Coordinator Library Section at CEU MALOLOS",
                "Mrs. Jemelyn O. Garcia is the Academic Coordinator of Community Outreach Section at CEU MALOLOS",
                "Mrs. Shella Marie S. Ignacio is the Head of Tourism Program at CEU MALOLOS",
                "Mrs. Marietta C. Alvarez is the Head of Liberal Arts Program/ Mass Communication Laboratory at CEU MALOLOS",
                "Mrs. Amelia T. Valencia is the head of Marketing Placement at CEU MALOLOS",
                "Mrs. Elvira G. Borlongan is the head of Registrar at CEU MALOLOS",
                "Mrs. Ada Ruth A. Aguasian is the Academic Coordinator of Tourism Management at CEU MAKATI",
                "Dr. Maria Wanda I. Martinez is the Academic Coordinator of Community Nursing at CEU MAKATI",
                "Mr. Rommel Rufuz A. Lopez is the Academic Coordinator of Clinical Dentistry at CEU MAKATI",
                "Dr. Amelita M. Borlongan is the Academic Coordinator of Research at CEU MAKATI",
                "Ms. Annabelle is the Academic Coordinator of Physical Education at CEU MAKATI",
                "Mrs. Maria Victoria S. Coloma is the Academic Coordinator of Clinical Nursing at CEU MAKATI",
                "Dr. Maria Corazon L. Andoy is the Assistant to the Vice President at CEU MAKATI",
                "Mrs. Eleanor C. Reyes is the Coordinator of Science Laboratory at CEU MALOLOS",
                "Dr. Flora L. Camay is the Program Head of Alumni Relation and Education at CEU MALOLOS"
        };
String answer[] =
        {
                "True",//1
                "False",//2
                "False",//3
                "True",//4
                "True",//5
                "False",//6
                "False",//7
                "True",//8
                "True",//9
                "True",//10
                "True",//11
                "True",//12
                "True",//13
                "True",//14
                "True",//15
                "False",//16
                "False",//17
                "True",//18
                "True",//19
                "False",//20
                "False",//21
                "False",//22
                "False",//23
                "True",//24
                "True",//25
                "True",//26
                "True",//27
                "True",//28
                "True",//29
                "True",//30
                "True",//31
                "True",//32
                "False",//33
                "True",//34
                "False",//35
                "False",//36
                "False",//37
                "True",//38
                "True",//39
                "False",//40
                "False",//41
                "True",//42
                "False",//43
                "False",//44
                "True",//45
                "True",//46
                "True",//47
                "True",//48
                "True",//49
                "True",//50

        };
HashSet numbers = new HashSet();


int flag = 0;
Random rnd = new Random();
int flag2 = 0;
int correct = 0;
int wrong = 0;
int coins = 0;
int time = 0;
int credit = 0;

private boolean isPaused = false;
private long timeremaining = 0;

String Executives = "lock";
String Liberators = "lock";
String Travellers = "lock";
String Specialist = "lock";
MediaPlayer mpTimer;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_levelone);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    isPaused = false;

    SharedPreferences loadGame = getSharedPreferences("Game", MODE_PRIVATE);
    credit = loadGame.getInt("savedPlayerCredit", 0);
    time = loadGame.getInt("savedPlayerTime", 0);

    SharedPreferences loadGame2 = getSharedPreferences("Theme", MODE_PRIVATE);
    Executives = loadGame2.getString("Executives", "lock");
    Liberators = loadGame2.getString("Liberators", "lock");
    Specialist = loadGame2.getString("Specialist", "lock");
    Travellers = loadGame2.getString("Travellers", "lock");

    final MediaPlayer mpWrong = MediaPlayer.create(this, R.raw.wrong);
    final MediaPlayer mpCorrect = MediaPlayer.create(this, R.raw.correct);
    final MediaPlayer mpNormal = MediaPlayer.create(this, R.raw.normal);
    mpTimer = MediaPlayer.create(this, R.raw.timer);


    tv1 = (TextView) findViewById(R.id.tv1);
    tvCred = (TextView) findViewById(R.id.tvCred);
    tvQuestion = (TextView) findViewById(R.id.tvQuestion);
    tvTimer = (TextView) findViewById(R.id.tvTimer);

    rb1 = (RadioButton) findViewById(R.id.rb1);
    rb2 = (RadioButton) findViewById(R.id.rb2);
    rg = (RadioGroup) findViewById(R.id.rg);

    btNext = (Button) findViewById(R.id.btNext);
    btPause = (Button) findViewById(R.id.btPause);
    btResume = (Button) findViewById(R.id.btResume);
    btNext.setBackgroundResource(R.drawable.next);

    ll = (LinearLayout) findViewById(R.id.ll);

    if (Executives.equals("active")) {
        time = time + 5000;
    } else if (Liberators.equals("active")) {
        coins = coins + 20;
    } else if (Travellers.equals("active")) {
        time = time + 5000;
    } else if (Specialist.equals("active")) {
        coins = coins + 20;
    } else {
        Toast.makeText(this, "Go!", Toast.LENGTH_SHORT).show();
    }

    flag2 = rnd.nextInt(50);
    numbers.add(flag2);
    tvQuestion.setText(questions[flag2]);
    tvCred.setText(String.valueOf(credit));
    mpTimer.start();


    timer = new CountDownTimer(time, 1000) {
        public void onTick(long millisUntilFinished) {
            if(isPaused)
            {
                timer.cancel();
            }
            else
            {
                tvTimer.setText("" + millisUntilFinished / 1000);
                timeremaining=millisUntilFinished;
            }
        }

        @Override
        public void onFinish() {

            Intent inResult = new Intent(getApplicationContext(), Results.class);
            SharedPreferences saveGame = getSharedPreferences("Game", MODE_PRIVATE);
            SharedPreferences.Editor editor = saveGame.edit();
            editor.putInt("savedPlayerCredit", credit);
            editor.putInt("savedPlayerCoins", coins);
            editor.putInt("savedPlayerCorrect", correct);
            editor.putInt("savedPlayerWrong", wrong);
            editor.apply();
            startActivity(inResult);
            mpTimer.stop();
        }
    }.start();

            btNext.setOnClickListener(new View.OnClickListener() {
                                  @Override
                                  public void onClick(View v) {
                                      btNext.setBackgroundResource(R.drawable.nextonclick);
                                      if (rg.getCheckedRadioButtonId() == -1) {
                                          Toast.makeText(getApplicationContext(), "Choose an Answer", Toast.LENGTH_LONG).show();
                                      } else {
                                          RadioButton uans = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
                                          String ansText = uans.getText().toString();
                                          if (ansText.equalsIgnoreCase(answer[flag2])) {
                                              while (numbers.contains(flag2)) {
                                                  flag2 = rnd.nextInt(50);
                                              }
                                              correct++;
                                              coins++;
                                              mpCorrect.start();
                                              Toast.makeText(getApplicationContext(), "Correct!", Toast.LENGTH_SHORT).show();
                                          } else {
                                              wrong++;
                                              mpWrong.start();
                                              Toast.makeText(getApplicationContext(), "Wrong!", Toast.LENGTH_SHORT).show();
                                          }
                                          flag++;
                                          flag2 = rnd.nextInt(50);

                                          if (flag < questions.length) {
                                              tvQuestion.setText(questions[flag2]);
                                              rb1.setChecked(false);
                                              rb2.setChecked(false);
                                              rg.clearCheck();
                                              btNext.setBackgroundResource(R.drawable.next);
                                          } else {
                                              Intent inResult = new Intent(getApplicationContext(), Results.class);
                                              SharedPreferences saveGame = getSharedPreferences("Game", MODE_PRIVATE);
                                              SharedPreferences.Editor editor = saveGame.edit();
                                              editor.putInt("savedPlayerCredit", credit);
                                              editor.putInt("savedPlayerCoins", coins + 100);
                                              editor.putInt("savedPlayerCorrect", correct);
                                              editor.putInt("savedPlayerWrong", wrong);
                                              editor.apply();
                                              timer.cancel();
                                              startActivity(inResult);
                                              mpTimer.stop();
                                          }
                                      }
                                      mpNormal.start();
                                  }
                              });
    btPause.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v) {
            isPaused = true;
            mpTimer.stop();
        }
    });
    btResume.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v){
            isPaused = false;
            mpTimer.start();
        }
    });
}

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle("Quit");
    builder.setMessage("Are you sure you want to Quit?");

    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            timer.onFinish();
        }
    });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            dialog.dismiss();
        }
    });

    AlertDialog alert = builder.create();
    alert.show();
}

@Override
protected void onStop() {
    super.onStop();
    timer.cancel();
    mpTimer.stop();
}

@Override
protected void onUserLeaveHint() {
    super.onUserLeaveHint();

}
  }
  • http://stackoverflow.com/questions/8306374/android-how-to-pause-and-resume-a-count-down-timer – X3Btel Mar 08 '16 at 11:07

1 Answers1

1

This is how I would do it. I would add something to the onTick handler to save the progress of the timer in your class ( Something like timeLeft = millisUntilFinished / 1000;)

When you want to pause the timer, do timer.cancel(). And when you want to continue running the timer, create a new timer with the saved number of milliseconds left.

This way, you don't need to worry about if the timer is still running when it should be paused, and passing extra values to the CountDownTimer.

EDIT:

You can create a private method to create a new CountDownTimer when you need it:

private CountDownTimer createTimer(int time){
return new CountDownTimer(time*1000, 1000) {
    @Override
        public void onTick(long millisUntilFinished) {
            tvTimer.setText("" + millisUntilFinished / 1000);
            timeLeft = millisUntilFinished / 1000;
    }

    @Override
    public void onFinish() {
        //Do what you want, cancel the timer...
    }
}.start();

Add a global variable

private CountDownTimer timer;

And when ever you need to create a CountDownTimer do:

timer = createCountDownTimer(yourTime);

And if you want to pause do timer.cancel();

Spirrow
  • 1,120
  • 6
  • 18
  • at the declaration on top u see i still have private long timeremaining i already did what u say... i make newcountdowntimer on bt resume but when i press resume when i did what u say what happen is the isPause goes false which makes the first timer active again and because i set the btresume to make a new countdown the tvTimer displays both time on the countdowntimers for example i pause the first timer at 10 seconds then i pause for 5 seconds then i hit resume the 2nd timer is created in 10 seconds and the first timer is in 5 sec so tvTimer displays both it goes like 10 5 9 4 8 3 – Tj Estrella Manzano Mar 08 '16 at 11:24
  • You don't need any boolean isPaused. You have to cancel the countDownTimer when you to pause it, and create a new one when you want to restart the timer. I will update my answer to make it more clear to you – Spirrow Mar 08 '16 at 11:27
  • ya tho i made it before u put the code :P thanks tho u helped me alot haha – Tj Estrella Manzano Mar 08 '16 at 13:09