CountDownTimer not counting down but jumping straight to finish() method - android

I have an app that I am creating that will eventually, be a countdown timer with multiple stores of times so that the user will select the one to use and then start the countdowntimer. The issue that I am having is that the call to the countDownTimer.start(); works but the timer jumps to the onfinish(). I placed log.i's within the override onTick function and those Log.i's did not appear in logcat, which leads me to believe that something went wrong in the logic and that the countdowntimer method did not see something to count down and dropped to the onfinish.
That being said, please see the entire app below:
package com.vertygoeclypse.multitimer;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.TextView;
public class MainActivity extends Activity implements NumberPicker.OnValueChangeListener, OnClickListener{
Button dgbtn, abbtn, exbtn, cvbtn, canlbtn, sbtbtn, starest;
EditText tagvalue;
TextView tgview, minview, secview, timeRemaining;
NumberPicker minnp, secnp;
Dialog cusd;
private MultiCountDownTimer countDownTimer;
private long timeElapsed;
private boolean timerHasStarted = false;
private TextView timeElapsedView;
long startTime;
long interval=100;
long coversionvalues=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dgbtn = (Button) findViewById(R.id.dialogbtn);
abbtn = (Button) findViewById(R.id.aboutbtn);
exbtn = (Button) findViewById(R.id.exitbtn);
cvbtn = (Button) findViewById(R.id.clrvaluesbtn);
starest = (Button) findViewById(R.id.startresetbtn);
tgview = (TextView) findViewById(R.id.tagview);
minview = (TextView) findViewById(R.id.minview);
secview = (TextView) findViewById(R.id.seecview);
timeRemaining = (TextView) findViewById(R.id.timeremainingview);
timeElapsedView = (TextView) findViewById(R.id.countdowntimer);
dgbtn.setOnClickListener(this);
abbtn.setOnClickListener(this);
exbtn.setOnClickListener(this);
cvbtn.setOnClickListener(this);
starest.setOnClickListener(this);
countDownTimer = new MultiCountDownTimer(startTime, interval);
if(startTime==0){
starest.setEnabled(false);
}else if(startTime>0){
starest.setEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// TODO Auto-generated method stub
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.dialogbtn:
showDialog();
break;
case R.id.exitbtn:
finish();
case R.id.clrvaluesbtn:
tgview.setText("");
minview.setText("");
secview.setText("");
break;
case R.id.cancelbtn:
cusd.dismiss();
case R.id.submitbtn:
tgview.setText(String.valueOf(tagvalue.getText()));
minview.setText(String.valueOf(minnp.getValue()));
secview.setText(String.valueOf(secnp.getValue()));
int val1 = Integer.parseInt(String.valueOf(minnp.getValue()));
int val2 = Integer.parseInt(String.valueOf(secnp.getValue()));
int val3 = (val1*60)*1000;
int val4 = val2*1000;
coversionvalues = Long.valueOf(String.valueOf(val3+val4));
startTime = coversionvalues;
starest.setEnabled(true);
cusd.dismiss();
break;
case R.id.startresetbtn:
if(!timerHasStarted){
countDownTimer.start();
timerHasStarted = true;
starest.setText("Start");
} else {
countDownTimer.cancel();
timerHasStarted = false;
starest.setText("Reset");
}
}
}
public void showDialog(){
cusd = new Dialog(MainActivity.this);
cusd.setTitle("Tag and Timer Selector");
cusd.setContentView(R.layout.dialogbox);
canlbtn = (Button) cusd.findViewById(R.id.cancelbtn);
sbtbtn = (Button) cusd.findViewById(R.id.submitbtn);
minnp = (NumberPicker) cusd.findViewById(R.id.numberPicker1);
secnp = (NumberPicker) cusd.findViewById(R.id.numberPicker2);
tagvalue = (EditText) cusd.findViewById(R.id.tagname);
canlbtn.setOnClickListener(this);
sbtbtn.setOnClickListener(this);
minnp.setMaxValue(59);
minnp.setMinValue(0);
minnp.setWrapSelectorWheel(false);
minnp.setOnValueChangedListener(this);
secnp.setMaxValue(59);
secnp.setMinValue(0);
secnp.setWrapSelectorWheel(false);
secnp.setOnValueChangedListener(this);
cusd.show();
}
public class MultiCountDownTimer extends CountDownTimer{
public MultiCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
#Override
public void onTick(long millisUntilFinished)
{
Log.i("VertygoEclypse", String.valueOf(millisUntilFinished));
timeRemaining.setText("Time remain:" + millisUntilFinished);
timeElapsed = startTime - millisUntilFinished;
Log.i("VertygoEclypse", String.valueOf(timeElapsed));
timeElapsedView.setText("Time Elapsed: " + String.valueOf(timeElapsed));
}
#Override
public void onFinish()
{
timeRemaining.setText("Time's up!");
timeElapsedView.setText("Time Elapsed: " + String.valueOf(startTime));
}
}
}

For startTime set some value, It cannot be zero. Actually startTime is the time in future when the countdown timer should stop or finish. if possible please change it to finish time
countDownTimer = new MultiCountDownTimer(startTime, interval);

Related

App crashes if no answer is given

My app is a timed math game. Answer as many questions as you can before the timer runs out. When the time runs out, The GameOverActivity is now the current activity. I've realized that if I give no answer, the app will crash. If I give at least 1 answer, the app doesn't crash and everything is normal. I'm not sure where the flaw in my code exista.
This is the Main Activity
package stormy.incremental.randomtest;
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.Random;
public class FastMathActivity extends AppCompatActivity {
int rand1, rand2, randDecider, correctAnswer, falseAnswer, problemsSolved;
String response,sumStr;
MyCountDownTimer myCountDownTimer;
int score;
Random r;
TextView randTV1, randTV2, scoreTV, sumTV, problemsSolvedTV, timerTV;
Button choice1, choice2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_test);
problemsSolved =0;
falseAnswer = 1;
//Initializing TextViews
timerTV = ((TextView) findViewById(R.id.timer));
randTV1 = ((TextView) findViewById(R.id.rand1));
randTV2 = ((TextView) findViewById(R.id.rand2));
sumTV = ((TextView) findViewById(R.id.sum));
scoreTV = ((TextView) findViewById(R.id.score));
problemsSolvedTV = ((TextView) findViewById(R.id.problemsSolved));
choice1 = ((Button) findViewById(R.id.choice1));
choice2 = ((Button) findViewById(R.id.choice2));
//Initializing a Random
r = new Random();
//Set the first question
setRandomProblem();
//Starting the timer
myCountDownTimer = new MyCountDownTimer(timerTV, 5000, 1000);
myCountDownTimer.start();
// Button Listeners
choice1.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
checkResponse((Button)v);
setRandomProblem();
}
});
choice2.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
checkResponse((Button)v);
setRandomProblem();
}
});
}
public void checkResponse(Button v) {
//Convert the response and correctAnswer to String in order to compare values
response = v.getText().toString();
sumStr = Integer.toString(correctAnswer);
//If the user clicks the correct answer, increment score
if ((response.equals(sumStr))) {
score++;
scoreTV.setText(score+"");
}
//Increment the total amount of problems solved
problemsSolved++;
problemsSolvedTV.setText(problemsSolved+"");
//Keep track of the score within the timer
myCountDownTimer.recordScore(score,problemsSolved);
}
private void setRandomProblem() {
//Assigning random values to ints
rand1 = r.nextInt(5 - 1) + 1;
rand2 = r.nextInt(5 - 1) + 1;
randDecider = r.nextInt(2) + 1;
//The correctAnswer of the randoms
correctAnswer = rand1 + rand2;
//Setting the texts of the random values
randTV1.setText(rand1 + "");
randTV2.setText(rand2 + "");
//If the random deciding number is 1, set answer on choice1
if (randDecider == 1) {
choice1.setText(correctAnswer + "");
choice2.setText(correctAnswer + falseAnswer + "");
}
//If the random deciding number is 2, set answer on choice2
else {
choice1.setText(correctAnswer + falseAnswer + "");
choice2.setText(correctAnswer + "");
}
}
#Override
public void onStop(){
super.onStop();
//Stop the timer
myCountDownTimer.cancel();
}
}
This is the GameOverActivity
package stormy.incremental.randomtest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
/**
* Created by kamalu on 12/25/2017.
*/
public class GameOverActivity extends AppCompatActivity {
TextView scoreTV, problemsSolvedTV, percentageTV;
int score, problemsSolved, percentage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover);
//Initializing TextViews
scoreTV = ((TextView)findViewById(R.id.score));
problemsSolvedTV = ((TextView)findViewById(R.id.problemsSolved));
percentageTV = ((TextView)findViewById(R.id.percentage));
//Opening Bundle and assigning values
Bundle extras = getIntent().getExtras();
score = extras.getInt("score");
problemsSolved = extras.getInt("problemsSolved");
//calculating the accuracy
percentage = (score/problemsSolved)*100;
//Displaying the score
percentageTV.setText(percentage+"");
scoreTV.setText(score+"");
problemsSolvedTV.setText(problemsSolved+"");
}
//Start the game over
public void retry(View v){
Intent retryIntent = new Intent(GameOverActivity.this, FastMathActivity.class);
startActivity(retryIntent);
}
public void onBackPressed()
{
}
}
This is the Timer. I believe it to be important to note that the onFinish() method in this class starts the GameOverActivity.
package stormy.incremental.randomtest;
import android.content.Intent;
import android.os.CountDownTimer;
import android.widget.TextView;
public class MyCountDownTimer extends CountDownTimer {
TextView textCounter;
int score,problemsSolved;
public MyCountDownTimer(TextView textCounter, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
this.textCounter = textCounter;
}
#Override
public void onTick (long millisUntilFinished){
textCounter.setText(String.valueOf(millisUntilFinished / 1000));
}
#Override
public void onFinish () {
Intent gameOverIntent = new Intent(textCounter.getContext(), GameOverActivity.class);
gameOverIntent.putExtra("score", score);
gameOverIntent.putExtra("problemsSolved", problemsSolved);
textCounter.getContext().startActivity(gameOverIntent);
}
//Keep track of the scores
public void recordScore(int score,int problemsSolved){
this.problemsSolved = problemsSolved;
this.score = score;
}
}
You should check:
//calculating the accuracy
percentage = (score/problemsSolved)*100;
if problemsSolved = 0, your app will crash with exeptions: java.lang.ArithmeticException
You can refer:
if (problemSolved != 0){
//calculating the accuracy
percentage = (score/problemsSolved)*100;
} else {
// handle with problemSolved = 0;
}
I hope it can help your problem!

How to tell when during countDownTimer() method a user presses a button?

I Have countDownTimer() method and want to print a certain toast if the user presses the button when the timer is at 10 or 9 seconds left. I am trying to read the time by reading the textview of the timer in the gameButton() method but it only prints the fail toast and not the pass toast. So why can I not do this? And also how can I get it to work? Thanks.
import android.app.Activity;
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 android.widget.Toast;
public class GameScreen extends Activity {
private TextView time;
private Button start;
private Button cancel;
private Button gameButton;
private CountDownTimer countDownTimer;
private View.OnClickListener btnClickListener = new View.OnClickListener(){
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.start_ID :
start();
break;
case R.id.cancel :
cancel();
break;
case R.id.gameButton_ID :
gameButton();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_screen);
start = (Button) findViewById(R.id.start_ID);
start.setOnClickListener(btnClickListener);
cancel = (Button) findViewById(R.id.cancel);
cancel.setOnClickListener(btnClickListener);
time = (TextView) findViewById(R.id.time);
gameButton = (Button) findViewById(R.id.gameButton_ID);
gameButton.setOnClickListener(btnClickListener);
}
public void start(){
time.setText("15");
countDownTimer = new CountDownTimer(15 * 1000, 1000) {
#Override
public void onTick(long millsUntilFinished){
time.setText("" + millsUntilFinished / 1000);
/* gameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
//if(time.getText() == "10" || time.getText() == "9" ){
Toast.makeText(new GameScreen(), "This is my Toast message!", Toast.LENGTH_LONG).show();
//}
}
}); */
}
public void onFinish(){
time.setText("Done !");
}
};
countDownTimer.start();
}
private void cancel(){
if(countDownTimer != null){
countDownTimer.cancel();
countDownTimer = null;
}
}
private void gameButton(){
if(time.getText() == "10" || time.getText() == "9" ){
Toast.makeText(getApplicationContext(), "PASS", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "FAIL", Toast.LENGTH_SHORT).show();
}
}
}
Use equals method not == operator
time.getText().equals("10") || time.getText().equals("9")
See What is the difference between == vs equals() in Java?

Want button to be visible after being invisible

I have a problem with a button to be invisible when I want. In my if statement I have declared the exerciseButtonDone to first to be invisible but then after the final countdown I want it to become visible.
As my code is right now the button is visible all the time.
package org.example.anders.eazy;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.os.Vibrator;
import java.util.concurrent.TimeUnit;
public class ExerciseActivity extends Activity {
String[] exerciseList;
TextView textTimer,workoutTextview,exerciseTextView;
int setsChosen;
int counter = 0;
int timeChosen;
boolean togglebuttonpress;
Button exerciseButtonDone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
exerciseList = getResources().getStringArray(R.array.heavy_chest_arms);
setContentView(R.layout.activity_exercise);
exerciseButtonDone=(Button)findViewById(R.id.buttonActiveExcercise);
Intent intent = getIntent();
String selectedWorkout = intent.getExtras().getString("workoutName");
togglebuttonpress=intent.getExtras().getBoolean("togglebuttonPress");
textTimer = (TextView) findViewById(R.id.timeUntilFinished);
//workoutTextview = (TextView) findViewById(R.id.workoutChosen);
//workoutTextview.setText(selectedWorkout);
if(togglebuttonpress){
exerciseButtonDone.setVisibility(View.INVISIBLE);
setsChosen =intent.getExtras().getInt("setsChosen");
int timePass = intent.getExtras().getInt("timeChosen");
timeChosen=timePass;
counter = 0;
runCountDownTimer();
exerciseButtonDone.setVisibility(View.VISIBLE);
}
else {
textTimer.setText("");
exerciseButtonDone.setVisibility(View.VISIBLE);
}
//exerciseTextView= (TextView) findViewById(R.id.exerciseNow);
//exerciseTextView.setText(exerciseList[i]);
}
public void runCountDownTimer() {
if (counter < setsChosen) {
new CountDownTimer(timeChosen * 60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
String hms = String.format("%02d:%02d",
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);
textTimer.setText(hms);
}
#Override
public void onFinish() {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
counter++;
v.vibrate(500);
runCountDownTimer();
}
}.start();
}
textTimer.setText("Complete");
}
}
You are setting the button invisible and then immediately visible.
if(togglebuttonpress){
exerciseButtonDone.setVisibility(View.INVISIBLE);
...
exerciseButtonDone.setVisibility(View.VISIBLE);
}
move exerciseButtonDone.setVisibility(View.VISIBLE); from its current location to where the countdown timer actually finishes, which I now see is runCountDownTimer()
if (counter < setsChosen) {
new CountDownTimer(timeChosen * 60000, 1000) {
...
}
} else {
exerciseButtonDone.setVisibility(View.VISIBLE);
}
you'll still need to make execerciseButtonDone final... and move it to the right scope, thank you alex. It needs to be a class variable, over by say boolean togglebuttonpress;
you COULD do findViewById again, but that's redundant and unnecessary.
I added an if statement that checked if loop was done. It worked.
public void onFinish() {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
counter++;
v.vibrate(500);
runCountDownTimer();
if (counter == setsChosen)
{
exerciseButtonDone.setVisibility(View.VISIBLE);
}
}

How to stop a thread(progressbar) in android

i have made a countdown timer using progressbar and a thread,Now i want to stop the progress at the same time when user clicks on a button.I have tried thread.stop(),but it says there is .no such method,I have tried interruot method too with no luck,So can any buddy please help me by viewing my code.My code is as below:
code
package com.amar.lyricalgenius;
import com.amar.lyricalgenius.LoadingActivity.MyCountDownTimer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class SinglePlayerOption extends Activity implements OnClickListener {
// visible gone
private int progressStatus = 0;
private Handler handler = new Handler();
Intent i;
TextView text_player_second;
ImageView vs_word;
ImageView player_second_pic, player_second_box;
ImageButton red_point1;
TextView text_number_pt1;
TextView text_number1;
ProgressBar pg_loading;
private CountDownTimer countDownTimer;
TextView timer_text;
private final long startTime = 8 * 1000;
private final long interval = 1 * 1000;
Button opt_1, opt_2, opt_3, opt_4;
Thread splashThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.single_player_option);
init();
}
private void init() {
// TODO Auto-generated method stub
text_player_second = (TextView) findViewById(R.id.text_player_second);
vs_word = (ImageView) findViewById(R.id.vs_word);
player_second_pic = (ImageView) findViewById(R.id.player_second_pic);
player_second_box = (ImageView) findViewById(R.id.player_second_box);
red_point1 = (ImageButton) findViewById(R.id.red_point1);
text_number_pt1 = (TextView) findViewById(R.id.text_number_pt1);
text_number1 = (TextView) findViewById(R.id.text_number1);
opt_1 = (Button) findViewById(R.id.option_1);
opt_2 = (Button) findViewById(R.id.option_2);
opt_3 = (Button) findViewById(R.id.option_3);
opt_4 = (Button) findViewById(R.id.option_4);
opt_1.setOnClickListener(this);
opt_2.setOnClickListener(this);
opt_3.setOnClickListener(this);
opt_4.setOnClickListener(this);
text_player_second.setVisibility(View.GONE);
vs_word.setVisibility(View.GONE);
player_second_pic.setVisibility(View.GONE);
player_second_box.setVisibility(View.GONE);
red_point1.setVisibility(View.GONE);
text_number_pt1.setVisibility(View.GONE);
text_number1.setVisibility(View.GONE);
countDownTimer = new MyCountDownTimer(startTime, interval);
timer_text.setText(timer_text.getText()
+ String.valueOf(startTime / 1000));
countDownTimer.start();
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
// current value in the text view
handler.post(new Runnable() {
public void run() {
pg_loading.setProgress(progressStatus);
}
});
try {
// Sleep for 200 milliseconds.
// Just to display the progress slowly
Thread.sleep(62);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
splashThread = new Thread() {
public void run() {
try {
sleep(6000);
// Utils.systemUpgrade(SplashActivity.this);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent intent = null;
intent = new Intent(SinglePlayerOption.this,
NoResponseActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
finish();
}
};
splashThread.start();
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i;
switch (v.getId()) {
case R.id.option_1:
splashThread.stop();
countDownTimer.onFinish();
Toast.makeText(SinglePlayerOption.this,
timer_text.getText().toString(), 1).show();
i = new Intent(SinglePlayerOption.this,
DialogLeaderboardActivity.class);
startActivity(i);
break;
}
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
timer_text.setText("Time's up!");
}
#Override
public void onTick(long millisUntilFinished) {
timer_text.setText("" + millisUntilFinished / 1000);
}
}
}
Thread th = new Thread(new Runnable() {
public void run() { ....
th.start();//starts
th.interrupt();//this stops.
and use
while (progressStatus < 100 && (!Thread.currentThread().isInterrupted())){....
instead of
while (progressStatus < 100) {....
Now i want to stop the progress at the same time when user clicks on
a button.I have tried thread.stop()
Thread.stop() is deprecated and you should not use it. The basic concept to understand is that a thread terminates is execution when the last line of code of his run method is executed. In the case of your "ProgressBar Thread*, when the user press the button, you have to set the exit condition of your while-loop (progressStatus = 100) in order to make it terminate

How to stop a countdown timer.....?

I am having problem in stopping a CountDownTimer. I have searched a lot but couldn't understand how to do that.
Below is my MainActivity. How can I stop the timer if RadioButton b is pressed?
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView mTextField;
RadioButton a, b, c, d, e;
final static long interval = 1000;
long timeout = 15000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextField = (TextView) findViewById(R.id.tv);
a = (RadioButton) findViewById(R.id.rB1a);
b = (RadioButton) findViewById(R.id.rB2a);
c = (RadioButton) findViewById(R.id.rB3a);
d = (RadioButton) findViewById(R.id.rB4a);
e = (RadioButton) findViewById(R.id.rB5a);
//Timer timer = new Timer();
//timer.scheduleAtFixedRate(task, interval, interval);
TimerTask task = new TimerTask() {
#Override
public void run() {
timeout = timeout - interval;
if (timeout == 0) {
this.cancel();
displayText("finished");
return;
}
if (timeout >= 0) {
displayText("time remaining: " + String.valueOf(timeout / 1000));
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), "Wrong Answer!!! ", Toast.LENGTH_LONG).show();
Intent openWordlist = new Intent("com.example.the_vocab_master.AA");
startActivity(openWordlist);
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), "GREAT...!!! ", Toast.LENGTH_LONG).show();
}
});
}
//displayText("time remaining: " + String.valueOf(timeout / 1000));
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, interval, interval);
}
private void displayText(final String text) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
mTextField.setText(text);
}
});
}
}
To cancel the timer use
timer.cancel();
in your onClick listener. It's very difficult to see in your code, because the indentation is very bad, but I think you need to declare your timer variable in the class, instead of in onCreate();
Additionally, I'd suggest you to take both setOnClickListener calls OUTSIDE of the timer run() method. What you're doing doesn't make sense.

Categories

Resources