Stop Android CountDownTimmer when another button is pressed - android

So I designed an Android application about a year ago now in Android Studio to take care of some things at my college. However, I never "completely finished" it. The one thing that it is missing for me is when I click a button it starts a timer and outputs a string. However, if I press another button before that timer is up, it will say both at the same time. In looking online, I haven't found exactly what I was looking for so I thought I would open it up to the Stackoverflow community and maybe you can guide me in the right direction. Now for the code.
package com.example.james.texttospeech;
import android.os.Bundle;
import android.app.Activity;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.view.View;
import android.widget.EditText;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.content.Intent;
import java.util.Locale;
import android.widget.Toast;
import android.os.CountDownTimer;
public class MainActivity extends Activity implements OnClickListener, OnInitListener {
//TTS object
private TextToSpeech myTTS;
//status check code
private int MY_DATA_CHECK_CODE = 0;
//create the Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get a reference to the button element listed in the XML layout
Button speakButton = (Button)findViewById(R.id.speak);
//listen for clicks
speakButton.setOnClickListener(this);
//check for TTS data
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
}
//respond to button clicks
public void onClick(View v) {
//get the text entered
EditText enteredText = (EditText)findViewById(R.id.enter);
String words = enteredText.getText().toString();
speakWords(words);
}
public void BRC (View view) {
new CountDownTimer(65000, 6000) {
public void onTick(long millisUntilFinished) {
String words1 = ("BRC will form up in" + millisUntilFinished / 6000 + " minutes");
speakWords(words1);
}
public void onFinish() {
String words2 = ("BRC will form up right away");
speakWords(words2);
}
}.start();
}
public void SRC (View view1) {
new CountDownTimer(65000, 6000) {
public void onTick(long millisUntilFinished) {
String words3 = ("SRC will form up in" + millisUntilFinished / 6000 +" minutes");
speakWords(words3);
}
public void onFinish() {
String words4=("SRC will form up right away");
speakWords(words4);
}
}.start();
}
public void Taps (View view2) {
new CountDownTimer(65000, 6000) {
public void onTick(long millisUntilFinished) {
String words5 = ("Taps will sound in" + millisUntilFinished / 6000 +" minutes");
speakWords(words5);
}
public void onFinish() {
String words6=("Attention inside and outside of barracks the status in barracks is now Taps C C Q at the beginning of this turnout there was a status check");
speakWords(words6);
}
}.start();
}
public void Penalty_Tours (View view3) {
new CountDownTimer(65000, 6000) {
public void onTick(long millisUntilFinished) {
String words7 = ("P Tees will form up in" + millisUntilFinished / 6000 +" minutes");
speakWords(words7);
}
public void onFinish() {
String words8=("P Tees will form up right away");
speakWords(words8);
}
}.start();
}
public void Colors (View view4) {
String words9 = ("Colors Colors Colors");
speakWords(words9);
}
public void PTT (View view5) {
new CountDownTimer(65000, 6000) {
public void onTick(long millisUntilFinished) {
String words10 = ("P T T will form up in" + millisUntilFinished / 6000 +" minutes");
speakWords(words10);
}
public void onFinish() {
String words11=("P T T will form up right away");
speakWords(words11);
}
}.start();
}
//speak the user text
private void speakWords(String speech) {
//speak straight away
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
//act on result of TTS data check
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
//the user has the necessary data - create the TTS
myTTS = new TextToSpeech(this, this);
}
else {
//no data - install it now
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
}
//setup TTS
public void onInit(int initStatus) {
//check for successful instantiation
if (initStatus == TextToSpeech.SUCCESS) {
if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
}
else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...", Toast.LENGTH_LONG).show();
}
}
}
Any help would be greatly appreciated.
public void BRC(View view) {
int totaltime = 6500;
CountDownTimer mTimer = new CountDownTimer(totaltime, 6000) {
public void onTick(long millisUntilFinished) {
String words1 = ("BRC will form up in" + millisUntilFinished / 6000 + " minutes");
speakWords(words1);
}
public void onFinish() {
String words2 = ("BRC will form up right away");
speakWords(words2);
}
}.start();
void SRC() {
mTimer.cancel();
}
}

In MainActivity function ,declare a variable to define the status of each counter. In onTick() of all counters, make it check for the variable
Hope this help.
public class MainActivity extends Activity implements OnClickListener, OnInitListener {
//TTS object
private Boolean isBRCRunning = false;
private Boolean isPTTRunning = false;
private static CountDownTimer myBRC;
private static CountDownTimer myPTT;
//
//respond to button clicks
public void onClick(View v) {
// .....
// If BRC button
if(BRC button){
BRC();
isBRCRunning = true;
} else if (PTT button){
BRC();
isBRCRunning = true;
}
}
public void BRC () {
myBRC = new CountDownTimer(65000, 6000) {
public void onTick(long millisUntilFinished) {
String words1 = ("BRC will form up in" + millisUntilFinished / 6000 + " minutes");
MainActivity.logForDebug(MainActivity.TAG, words1);
// Control other timer
if(isPTTRunning){
myPTT.cancel();
isPTTRunning = false;
}
}
public void onFinish() {
String words2 = ("BRC will form up right away");
MainActivity.logForDebug(MainActivity.TAG, words2);
}
}.start();
}
public void PTT () {
myPTT = new CountDownTimer(65000, 6000) {
public void onTick(long millisUntilFinished) {
String words1 = ("BRC will form up in" + millisUntilFinished / 6000 + " minutes");
MainActivity.logForDebug(MainActivity.TAG, words1);
// Control other timers
if(isBRCRunning){
myBRC.cancel();
isBRCRunning = false;
}
}
public void onFinish() {
String words2 = ("BRC will form up right away");
MainActivity.logForDebug(MainActivity.TAG, words2);
}
}.start();
}
}

Related

Android Studio counter

I have a problem with a small counter system that I made in Android Studio the problem is that I don't know how to do the counter plus 1.5 because now it is all the time when I press the plus button it does all the time 1 there but that must be 1.5 in the script below geld++; ensures that 1 is added all the time when you press the button that just works well but I don't want 1 but I want 1.5 all the time but I can't find a solution anywhere. So I hope someone can help. Thanks in advance!
package com.example.melkanalysetimer;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class wit extends AppCompatActivity {
private TextView countdownText;
private Button countdownButton;
private Button krat;
private Button remove;
private TextView scoreb;
private TextView money;
private TextView reset;
private CountDownTimer countDownTimer;
private long timeLeftInMilliseconds = 960000;
private boolean timerRunning;
private static final long START_TIME_IN_MILLIS = 960000;
int score = 0;
int geld = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wit);
countdownText = findViewById(R.id.countdown_text);
countdownButton = findViewById(R.id.countdown_button);
krat = findViewById(R.id.b_add);
scoreb = findViewById(R.id.tv_score);
remove = findViewById(R.id.b_remove);
money = findViewById(R.id.ssgeld);
reset = findViewById(R.id.button_reset);
scoreb.setText("Kratjes: "+ score);
money.setText("Geld: "+ geld);
krat.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
score++;
scoreb.setText("Kratjes: "+ score);
geld++;
money.setText("Geld: "+ geld);
}
});
remove.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
score--;
scoreb.setText("Kratjes: "+ score);
geld--;
money.setText("Geld: "+ geld);
}
});
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
resetTimer();
}
});
countdownButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startStop();
}
});
updateTimer();
}
public void startStop() {
if (timerRunning) {
stopTimer();
} else {
startTimer();
}
}
public void startTimer() {
countDownTimer = new CountDownTimer(timeLeftInMilliseconds, 1000) {
#Override
public void onTick(long l) {
timeLeftInMilliseconds = l;
updateTimer();
}
#Override
public void onFinish() {
}
}.start();
countdownButton.setText("PAUZE");
timerRunning = true;
}
public void stopTimer() {
countDownTimer.cancel();
countdownButton.setText("START");
timerRunning = false;
}
public void resetTimer() {
timeLeftInMilliseconds = START_TIME_IN_MILLIS;
updateTimer();
}
public void updateTimer() {
int minutes = (int) timeLeftInMilliseconds / 60000;
int seconds = (int) timeLeftInMilliseconds % 60000 / 1000;
String timeLeftText;
timeLeftText = "" + minutes;
timeLeftText += ":";
if (seconds < 10) timeLeftText += "0";
timeLeftText += seconds;
countdownText.setText(timeLeftText);
}
}
First you need to change Int to Double like
double score = 0.00;
Then Increment/Decrement like this
Decrement
remove.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
//check if score is less then 0
if(score > 1.5){
score = score - 1.5;
}
scoreb.setText("Kratjes: "+ score);
geld--;
money.setText("Geld: "+ geld);
}
});
Increment
krat.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
score = score + 1.5;
scoreb.setText("Kratjes: "+ score);
geld++;
money.setText("Geld: "+ geld);
}
});

Loop a Countdown timer X number of times,

I'm trying to loop my countdown timer for a specific number of times, but I'm not sure where I should add my for loop... Currently trying to do an interval timer function (I know there's a way to do it via Handler, but I'm still a beginner and got kind of confused on how I shoul use the handler)
I've tried adding it at '.start' and the StartTimer function but the countdown time still stays at 0. Would be great if any assistance is given as I'm still a beginner.. Thanks!
package com.example.bushykai.myapplication;
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;
public class Timer extends AppCompatActivity {
private static final long START_TIME_IN_MILLIS=10000;
private int sets = 3;
private TextView textViewCountdown;
private Button buttonStartPause;
private Button buttonReset;
private CountDownTimer countDownTimer;
private boolean timerRunning;
private long timeLeftInMillis = START_TIME_IN_MILLIS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
textViewCountdown = findViewById(R.id.countdownTimer);
buttonStartPause = findViewById(R.id.startPause);
buttonReset= findViewById(R.id.reset);
buttonStartPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (timerRunning) {
pauseTimer();
}
else {
startTimer();
}
}
});
buttonReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetTimer();
}
});
updateCountDownText();
}
private void pauseTimer() {
countDownTimer.cancel();
timerRunning = false;
buttonStartPause.setText("Start");
buttonReset.setVisibility(View.VISIBLE);
}
private void startTimer() {
countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
timerRunning = false;
buttonStartPause.setText("Start");
buttonStartPause.setVisibility(View.INVISIBLE);
buttonReset.setVisibility(View.VISIBLE);
}
}.start();
timerRunning = true;
buttonStartPause.setText("Pause");
buttonReset.setVisibility((View.INVISIBLE));
}
private void resetTimer() {
timeLeftInMillis = START_TIME_IN_MILLIS;
updateCountDownText();
buttonReset.setVisibility(View.INVISIBLE);
buttonStartPause.setVisibility(View.VISIBLE);
}
private void updateCountDownText() {
int minutes = (int) (timeLeftInMillis / 1000 ) / 60;
int seconds = (int) (timeLeftInMillis / 1000 ) % 60;
String timeLeftFormatted = String.format("%02d:%02d", minutes, seconds);
textViewCountdown.setText(timeLeftFormatted);
}
}
You have to add a Runnable Handler to your class try code below and modify with your Countdown Timer
public Handler timerHandler = new Handler();
public Runnable timerRunnable = new Runnable() {
#Override
public void run() {
//show alert or DO Whatever
}
};
public void timerStart() {
timerStop();
timerHandler.postDelayed(timerRunnable, Constants.TIMER_TIME_OUT);
}
public void timerStop() {
timerHandler.removeCallbacks(timerRunnable);
}

App crashes when countdowntimer.cancel() is used

I Want to create a timer which will run for 10 seconds. If the user have entered the correct answer the timer should restart. For that I have added cancel.countdowntimer(). But it's not working. The app crashes. Where should I use that countdowntimer.cancel() function? Should I use a method for countdowntimer.cancel()?
package com.example.vignesh.work;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
Button b1;
int loc;
int total=0;
int mark=0;
Runnable run;
Handler handler;
CountDownTimer countDownTimer;
TextView textView4,textView2,textView1,textView3;
Button b11,b22,b33,b44;
Random random = new Random();
ArrayList<Integer> answers = new ArrayList<Integer>();
public void nextQuestion() {
new CountDownTimer(10000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
textView3.setText(Long.toString(millisUntilFinished / 1000));
}
#Override
public void onFinish() {
textView3.setText("10");
}
}.start();
int a = random.nextInt(20) + 1;
int b = random.nextInt(20) + 1;
textView1.setText(Integer.toString(a) + "+" + Integer.toString(b));
loc = random.nextInt(4);
answers.clear();
for (int i = 0; i < 4; i++) {
if (i == loc) {
answers.add(a + b);
} else {
answers.add((a + b) + random.nextInt(10) + 1);
}
}
b11.setText(Integer.toString(answers.get(0)));
b22.setText(Integer.toString(answers.get(1)));
b33.setText(Integer.toString(answers.get(2)));
b44.setText(Integer.toString(answers.get(3)));
}
public void choose(View view)
{
if(view.getTag().toString().equals(Integer.toString(loc+1)))
{
textView4.setText("Correct");
mark++;
}
else
{
textView4.setText("Wrong");
}
total++;
try {
countDownTimer.cancel();
}
catch (Exception e)
{
Log.i("error",e.getMessage());
}
nextQuestion();
textView2.setText(Integer.toString(mark)+"/"+Integer.toString(total));
}
public void click(View view)
{
b1.setVisibility(view.INVISIBLE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.buttongo);
b11 = (Button)findViewById(R.id.optiona);
b22 = (Button)findViewById(R.id.optionb);
b33 = (Button)findViewById(R.id.option3);
b44 = (Button)findViewById(R.id.option4);
textView1=(TextView)findViewById(R.id.textView1);
textView2=(TextView)findViewById(R.id.textView2);
textView3=(TextView)findViewById(R.id.textView3);
textView4=(TextView)findViewById(R.id.textView4);
nextQuestion();
}
}
**AFTER ADDING EXCEPTIONAL HANDLING THE ERROR WAS:Attempt to invoke virtual method 'void android.os.CountDownTimer.cancel()' on a null object reference**
Thanks.
You instantiate your CountDownTimer in nextQuestion() method, however you do not assign it in the countDownTimer variable defined in the top of your class: CountDownTimer countDownTimer;
Change the code inside nextQuestion() method to:
countDownTimer = new CountDownTimer(10000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
textView3.setText(Long.toString(millisUntilFinished / 1000));
}
#Override
public void onFinish() {
textView3.setText("10");
}
};
countDownTimer.start();
Note that I am assigning the new CountDownTimer to countDownTimer variable and then start the timer by calling countDownTimer.start();.
Then check if countDownTimer is null before calling it to cancel:
if(countDownTimer != null) {
countDownTimer.cancel();
}
You are not initialising countDownTimer variable update your method like below and also check null before calling countDownTimer.cancel();
public void nextQuestion() {
countDownTimer = new CountDownTimer(10000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
textView3.setText(Long.toString(millisUntilFinished / 1000));
}
#Override
public void onFinish() {
textView3.setText("10");
}
}.start();
int a = random.nextInt(20) + 1;
int b = random.nextInt(20) + 1;
textView1.setText(Integer.toString(a) + "+" + Integer.toString(b));
loc = random.nextInt(4);
answers.clear();
for (int i = 0; i < 4; i++) {
if (i == loc) {
answers.add(a + b);
} else {
answers.add((a + b) + random.nextInt(10) + 1);
}
}
b11.setText(Integer.toString(answers.get(0)));
b22.setText(Integer.toString(answers.get(1)));
b33.setText(Integer.toString(answers.get(2)));
b44.setText(Integer.toString(answers.get(3)));
}

How to tell if button was not clicked in android?

I have a count down timer and if the user does not click this button on an even number I need to perform a certain method which will end my game. So basically if the user stops tapping I need the gameOver() method called.
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;
public static int count = 0;
int foo = Integer.parseInt(time.getText().toString());
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);
//this doesnt work and makes app crash when you hit start button
if((gameButton.isPressed() != true) && foo % 2 == 0){
gameOver();
}
}
public void onFinish(){
time.setText("Done !");
}
};
countDownTimer.start();
}
private void cancel(){
if(countDownTimer != null){
countDownTimer.cancel();
countDownTimer = null;
}
}
private void gameOver(){
Toast.makeText(getApplicationContext(), "You scored " + count, Toast.LENGTH_SHORT).show();
count = 0;
cancel();
}
private void gameButton(){
if(foo % 2 == 0 ) {
Toast.makeText(getApplicationContext(), "PASS", Toast.LENGTH_SHORT).show();
++count;
}
else{
gameOver();
}
}
}
What you can do is take one boolean called isClickedOnEvenNumber. Now when you press the button when even-number set isClickedOnEvenNumber as
isClickedOnEvenNumber = true;
Now check on every tick check that
if(isClickedOnEvenNumber)
//continue game
else
//end game
EDIT :
You can use a TimerTask that periodically verifies wether or not the Button was clicked. You do not need the counterBTnnotclicked variable any more.
So you can do something like this : (Am trying to write this quickly, so be aware of that)
class BtnClickIntegerHolder{
public int counterBtnClicked = 0;
}
class BtnClicksCheckerIntegerHolder{
public int btnClicks = 0;
}
final BtnClickIntegerHolder btnClickCounter = new BtnClickIntegerHolder();
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnClickCounter.counterBtnClicked = btnClickCounter.counterBtnClicked + 1;
}
});
int period = 10000; // repeat every 10 secs.
final BtnClicksCheckerIntegerHolder btnClicksHolder = new BtnClicksCheckerIntegerHolder();
btnClicksHolder.btnClicks = btnClickCounter.counterBtnClicked;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
if(btnClickCounter.counterBtnClicked == btnClicksHolder.btnClicks ){
//Button was not clicked
}
else{
//Button was clicked
}
btnClicksHolder.btnClicks = btnClickCounter.counterBtnClicked;
}
}, period, period);

What is wrong with my Text-To-Speech in my CountDownTimer?

Hey all, I'm trying to put text-to-speech in my CountDownTimer. I would like it to say "There are x seconds left" after a certain amount of time. I just started using TextToSpeech and I'm not really sure what I'm doing..
package com.android.countdown;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.speech.tts.TextToSpeech;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class countdown extends Activity implements TextToSpeech.OnInitListener{
CountDownTimer Counter1;
CountDownTimer Counter2;
CountDownTimer Counter3;
int Interval = 1;
TextToSpeech tts;
public String formatTime(long millis) {
String output = "0:00";
long seconds = millis / 1000;
long minutes = seconds / 60;
seconds = seconds % 60;
minutes = minutes % 60;
String secondsD = String.valueOf(seconds);
String minutesD = String.valueOf(minutes);
if (seconds < 10)
secondsD = "0" + seconds;
if (minutes < 10)
minutesD = "0" + minutes;
output = minutesD + " : " + secondsD;
return output;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Declare Start/Stop timer
Button btnstart = (Button)findViewById(R.id.btnstart);
Button btnstop = (Button)findViewById(R.id.btnstop);
//Text field to show time left
final TextView mCounter1TextField=(TextView)findViewById(R.id.counter1);
final TextView mCounter2TextField = (TextView)findViewById(R.id.counter2);
final TextView mCounter3TextField=(TextView)findViewById(R.id.counter3);
//Counter 1
Counter1 = new CountDownTimer(20000 , Interval) {
public void onTick(long millisUntilFinished){
mCounter1TextField.setText("Seconds left: " + formatTime(millisUntilFinished));
if (millisUntilFinished == 10000) {
instantiate();
}
}
public void onFinish() {
Counter1.start();
}
};
//Counter 2
Counter2 = new CountDownTimer(80000 , Interval) {
public void onTick(long millisUntilFinished) {
mCounter2TextField.setText("Seconds left: " + formatTime(millisUntilFinished));
}
public void onFinish() {
mCounter2TextField.setText("Finished!");
Counter2.start();
}
};
//Counter 3
Counter3 = new CountDownTimer(3000 , Interval) {
public void onTick(long millisUntilFinished) {
mCounter3TextField.setText("Seconds left: " + formatTime(millisUntilFinished));
}
public void onFinish() {
mCounter3TextField.setText("Finished!");
Counter3.start();
}
};
//Start Button
btnstart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Counter1.start();
Counter2.start();
Counter3.start();
}
});
//Stop Button
btnstop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Counter1.cancel();
Counter2.cancel();
Counter3.cancel();
if (tts != null) {
tts.stop();
tts.shutdown();
}
}
});
}
public void instantiate() {
tts = new TextToSpeech(this, this);
tts.setLanguage(Locale.US);
tts.speak("You have 10 seconds remaining", TextToSpeech.QUEUE_ADD, null);
}
#Override
public void onInit(int status) {
}
#Override
public void onDestroy() {
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
Your second argument in tts = new TextToSpeech(this, this) does not implement TextToSpeech.OnInitListener.
You need to have countdown or another class implement TextToSpeech.OnInitListener:
public class countdown extends Activity implements TextToSpeech.OnInitListener {
Then implement onInit() in said class:
void onInit(int status){
// implementation
}
And finally pass the class that implements OnInitListener into the TextToSpeech constructor:
// The second 'this' will be replaced with another class if you
// decide to use a class other than countdown to implement the interface.
tts = new TextToSpeech(this, this);
Check out the TextToSpeechActivity.java tutorial for a full working example.
EDIT
As NickT mentioned, you also need to add curly braces to your if statement in onTick:
if (millisUntilFinished == 10000) {
tts = new TextToSpeech(this, this);
tts.setLanguage(Locale.US);
tts.speak("You have 10 seconds remaining", TextToSpeech.QUEUE_ADD, null);
}
Else you'll execute setLanguage and speak always, which will give you a NullPointerException unless millisUntilFinished == 10000 is true.
http://developer.android.com/reference/android/speech/tts/TextToSpeech.OnInitListener.html
Another approach that doen't need to implement TextToSpeech.OnInitListener in your activity, meaning a cleaner code (In my opinion), is:
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status){
if(status == TextToSpeech.SUCCESS) {
Log.d("myapp", "TextToSpeech enabled");
}
}
});
If you want to "ask" for tts data. I do it this way:
// I have this code inside onCreate(), but you can call it elsewhere.
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, 6);
// Then, in the activity add this code:
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent intent) {
if (requestCode == 6) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status){
if(status == TextToSpeech.SUCCESS) {
Log.d("myapp", "TextToSpeech prepared");
}
}
});
}
}
}
Is almost the same as TextToSpeech.isLanguageAvailable(). I'm going to change it near the future.

Categories

Resources