I tried to set TTS's paras such as pitch and speech rate by pressing a button, but somehow nothing changes when I pressed it...
See the code following, what I planned is that once I press the button SetPara, the _pitch and _rate will be set to 0.5, and
tts.setPitch(_pitch);
tts.setSpeechRate(_rate);
will set TTS's pitch and speech rate to 0.5, but the problem now is that after I pressed the SetPara button the pitch and speech rate didn't change...
Please help me out :))))
package com.example.text2speechtrail;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;
private Button btnSetPara;
private EditText getPitch;
private EditText getRate;
public float _pitch;
public float _rate;
String _string_pitch = null;
String _string_rate = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
btnSpeak = (Button) findViewById(R.id.btnSpeak);
btnSetPara = (Button) findViewById(R.id.setPara);
txtText = (EditText) findViewById(R.id.txtText);
getPitch = (EditText) findViewById(R.id.getPitch);
getRate = (EditText) findViewById(R.id.getRate);
btnSetPara.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SetPara();
}
});
// button on click event
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
speakOut();
}
});
}
public void SetPara(){
_pitch = (float) 0.5;
_rate = (float) 0.5;
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.ENGLISH);
tts.setPitch(_pitch);
tts.setSpeechRate(_rate);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
btnSpeak.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
You need to set on click listener for your btnSetPara button
btnSetPara.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SetPara();
}
});
You do not need the param View in setPara
public void SetPara(){
_pitch = (float) 0.5;
_rate = (float) 0.5;
if (tts != null) {
tts.setPitch(_pitch);
tts.setSpeechRate(_rate);
}
}
private void speakOut() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
Related
I am building an app that reads SMS's by converting them to speech.
After installing the apk it runs but when I close it and try to open it again it crashes.
It gives an error message saying the app keeps closing.
When I set it to only read after a button click it was working fine but after I changed it to read on initialization this problem came about.
Please help.
package com.example.receiver3;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
ListView listView;
Button btConvert, btNext;
private static final int PERMISSION_REQUEST_READ_CONTACTS = 100;
ArrayList<String> smsList;
TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.idList);
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);
if (permissionCheck == PackageManager.PERMISSION_GRANTED){
initializeTextToSpeech(); //edit
showContact();
}
else{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, PERMISSION_REQUEST_READ_CONTACTS);
}
btConvert = findViewById(R.id.bt_stop);
btNext = findViewById(R.id.bt_next);
btConvert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get list value
for (String s : smsList) {
textToSpeech.stop();
}
}
});
Button button = (Button) findViewById(R.id.bt_next);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivity();
}
});
}
private void initializeTextToSpeech() { //edit
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS){
int lang = textToSpeech.setLanguage(Locale.UK);
}
}
});
}
public void openActivity(){
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_READ_CONTACTS){
showContact();
initializeTextToSpeech(); //edit
}
else {
Toast.makeText(this, "Permission Required", Toast.LENGTH_SHORT).show();
}
}
private void showContact() {
Uri inboxUri = Uri.parse("content://sms/inbox");
smsList = new ArrayList<>();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(inboxUri,null, null, null, null);
while (cursor.moveToNext()){
String number = cursor.getString(cursor.getColumnIndexOrThrow("address")).toString();
String body = cursor.getString(cursor.getColumnIndexOrThrow("body")).toString();
smsList.add("Number: "+number+ "\n" + "Body: "+body);
}
for (String s : smsList) {
textToSpeech.speak(s,TextToSpeech.QUEUE_ADD, null);
}
cursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,smsList);
listView.setAdapter(adapter);
}
public void speak() { //edit
for (String s : smsList) {
textToSpeech.speak(s,TextToSpeech.QUEUE_ADD, null);
}
}
#Override
protected void onPause() { //edit
super.onPause();
textToSpeech.stop();
}
#Override
protected void onStop() {
super.onStop();
textToSpeech.stop();
}
#Override
protected void onResume() { //edit
super.onResume();
showContact();
initializeTextToSpeech();
}
}
You are now calling showContact() which in turn calls textToSpeech.speak() before initialising the textToSpeech object with textToSpeech = new TextToSpeech().
The code works fine on the first run because the user hasn't given the requested permission yet and showContact() doesn't get called.
You need to change your onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.idList);
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);
// *** MOVE THIS UP HERE. ***
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS){
int lang = textToSpeech.setLanguage(Locale.UK);
return;
}
}
});
if (permissionCheck == PackageManager.PERMISSION_GRANTED){
showContact();
return;
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, PERMISSION_REQUEST_READ_CONTACTS);
}
btConvert = findViewById(R.id.bt_convert);
btNext = findViewById(R.id.bt_next);
btConvert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get list value
for (String s : smsList) {
textToSpeech.stop();
}
}
});
Button button = (Button) findViewById(R.id.bt_next);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivity();
}
});
}
But that alone won't be enough as TTS isn't ready immediately. It's usable only after the onInit() callback has run and you receive the TextToSpeech.SUCCESS state there.
So, if you want to speak something as soon as possible at application startup then it needs to be triggered from onInit().
Maybe you can think of something like:
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);
if (permissionCheck != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, PERMISSION_REQUEST_READ_CONTACTS);
}
And then:
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS){
int lang = textToSpeech.setLanguage(Locale.UK);
if (permissionCheck == PackageManager.PERMISSION_GRANTED){
showContact();
}
}
}
});
I don't see why would you have the return; calls at all. And actually in the original code the return; exits the onCreate() before even trying to initialize the TTS if the permission is already given.
When i try rotating the screen it does not erase the data, but when I go from the activity and back the counter value goes back to 0.
I have set make the method for saving the data, but it still doesnt save. Why is this?
package com.example.navjeevenmann.mytycoon;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button myButton;
private int Counter = 0;
private Button myButton2;
private TextView myTextView;
Handler handler = new Handler();
private int add = 0;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
Counter = savedInstanceState.getInt("Count");
add = savedInstanceState.getInt("Add");
}
setContentView(R.layout.activity_main);
myButton = (Button) findViewById(R.id.button);
myButton2 = (Button) findViewById(R.id.button2);
myTextView = (TextView) findViewById(R.id.textView);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Counter = ButtonCounter(Counter);
}
});
myButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
intent.putExtra("Count", Counter);
startActivity(intent);
finish();
}
});
handler.postDelayed(new Runnable() {
#Override
public void run() {
Counter = AutoCounter(Counter, add);
Display(Counter, myTextView);
handler.postDelayed(this, 100);
}
}, 10);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("Count", Counter);
savedInstanceState.putInt("Add", add);
super.onSaveInstanceState(savedInstanceState);
}
public int ButtonCounter(int Counter) {
Counter += 1;
return Counter;
}
public int AutoCounter(int Counter, int add) {
Counter += add;
return Counter;
}
public void Display(int Counter, TextView myTextView) {
String man = String.valueOf(Counter);
myTextView.setText("$" + man);
}
}
My code runs like that...
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt("Count", Counter);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null)
{
if (savedInstanceState.containsKey("Count"))
{
Counter = savedInstanceState.getInt("Count");
}
}
}
Difference is that i don't have final Bundle on create and i save it after super.onSave.. wich seems odd....
I am using the audiodispatcher from the TarsosDSPlibrary.
The pitchdetection is used to detect sounds from the mic. Once detected, it switches to the next activity (which is a Maths quiz). After completing the quiz on the next activity, it returns to this activity and starts the process all over again.
What is bugging me is that my APP is working 90% of the time when using the pitchdetection function. However, sometimes it doesn't work and throws an error as follows:
E/AudioRecord: start() status -38
and the app no longers switches to the next activity.
package com.humanfactorsandappliedcognitionlab.research.mathsapp;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.RunnableFuture;
import be.tarsos.dsp.AudioDispatcher;
import be.tarsos.dsp.AudioEvent;
import be.tarsos.dsp.io.android.AudioDispatcherFactory;
import be.tarsos.dsp.pitch.PitchDetectionHandler;
import be.tarsos.dsp.pitch.PitchDetectionResult;
import be.tarsos.dsp.pitch.PitchProcessor;
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
MediaPlayer notifySound;
MediaPlayer endSound;
AudioDispatcher dispatcherMAIN;
PitchProcessor pitchProcessorMAIN;
public boolean isListening = false;
TextToSpeech tts;
private int sensitivity = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notifySound = MediaPlayer.create(this, R.raw.samsung);
endSound = MediaPlayer.create(this, R.raw.ding);
OPTION = dbHandler.getOPTION();
tts = new TextToSpeech(this, this);
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run(){
}
});
}
#Override
public void onDone(String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run(){
startListenToTalk();
}
});
}
#Override
public void onError(String utteranceId) {
}
});
}
private void speakOut() {
Log.e("TTS", "SPEAKING...");
String text = "Please Say Continue to Proceed ";
HashMap<String, String> map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "");
tts.speak(text, TextToSpeech.QUEUE_FLUSH, map);
}
private void startListenToTalk() {
dispatcherMAIN = AudioDispatcherFactory.fromDefaultMicrophone(22050, 1024, 0);
pitchProcessorMAIN = new PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.FFT_YIN, 22050, 1024, new PitchDetectionHandler() {
#Override
public void handlePitch(PitchDetectionResult pitchDetectionResult,
AudioEvent audioEvent) {
final float pitchInHz = pitchDetectionResult.getPitch();
runOnUiThread(new Runnable() {
#Override
public void run() {
ImageButton buttonOK = (ImageButton) findViewById(R.id.buttonOK);
TextView textINPUT = (TextView)findViewById(R.id.textINPUT);
if (pitchInHz > sensitivity) {
Log.e("pitch : ", pitchInHz + "");
if (isListening) {
try {
dispatcherMAIN.stop();
Intent gotoMaths = new Intent(MainActivity.this, MathsActivity.class);
startActivity(gotoMaths);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
}
});
dispatcherMAIN.addAudioProcessor(pitchProcessorMAIN);
new Thread(dispatcherMAIN, "Audio Dispatcher").start();
isListening = true;
}
#Override
protected void onPause() {
super.onPause();
if (notifySound != null) {
notifySound.release();
}
if (endSound != null) {
endSound.release();
}
if (isListening) {
try {
dispatcherMAIN.stop();
} catch (Exception e) {
e.printStackTrace();
}
isListening = false;
}
finish();
}
#Override
public void onStop(){
super.onStop();
if (tts != null) {
tts.shutdown();
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
if(OPTION == "3") {
speakOut();
}
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
Below is my code.I am unable to hear the voice in my kitkat device.Toast is appearing but voice is not playing.I am following this tutorial
https://www.tutorialspoint.com/android/android_text_to_speech.htm
package com.example.insert;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
import android.widget.Toast;
import android.util.Log;
import java.lang.Object;
public class SecondActivity extends AppCompatActivity {
TextToSpeech t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
String emailid;
emailid = "Hi,say your email id";
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = t1.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(getApplicationContext(), "This language is not supported", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Initialization failed", Toast.LENGTH_SHORT).show();
}
}
});
// Toast.makeText(getApplicationContext(), emailid, Toast.LENGTH_SHORT).show();
t1.speak(emailid, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
protected void onDestroy() {
super.onDestroy();
// Don't forget to shutdown tts!
if (t1 != null) {
Log.e("TTS","speech on destroy");
t1.stop();
t1.shutdown();
}
}
}
I have followed this post on stackoverflow.
Android TTS doesn't speak
But i didn't understand gameover,line and definition_string.
guys help me
Here is my code. this code works on Nexus9.(Locale is Japan)
public class MainActivity extends AppCompatActivity{
static final String TAG = "TTS";
TextToSpeech mTts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String emailid;
emailid = "こんにちは";
mTts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.JAPAN);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(getApplicationContext(), "This language is not supported", Toast.LENGTH_SHORT).show();
}
else{
Log.v("TTS","onInit succeeded");
speak(emailid);
}
} else {
Toast.makeText(getApplicationContext(), "Initialization failed", Toast.LENGTH_SHORT).show();
}
}
});
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
void speak(String s){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.v(TAG, "Speak new API");
Bundle bundle = new Bundle();
bundle.putInt(TextToSpeech.Engine.KEY_PARAM_STREAM, AudioManager.STREAM_MUSIC);
mTts.speak(s, TextToSpeech.QUEUE_FLUSH, bundle, null);
} else {
Log.v(TAG, "Speak old API");
HashMap<String, String> param = new HashMap<>();
param.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_MUSIC));
mTts.speak(s, TextToSpeech.QUEUE_FLUSH, param);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
// Don't forget to shutdown tts!
if (mTts != null) {
Log.v(TAG,"onDestroy: shutdown TTS");
mTts.stop();
mTts.shutdown();
}
}
}
It takes some time to initialise. Put the speak code in onClick method. If you trigger that method on button click, it will speak.
someButton.setOnClickListener(new OnClickListener{
onClick(View view){
t1.speak(emailid, TextToSpeech.QUEUE_FLUSH, null);
}
}
I guess problem is with Locale.
Please print logs. try out following code.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
import android.widget.Toast;
public class SecondActivity extends AppCompatActivity {
TextToSpeech t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
String emailid;
emailid="Hi,say your email id";
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS) {
t1.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.d(TAG, "This Language is not supported");
}
}else{
Log.d(TAG, "Initilization Failed!");
}
}
});
Toast.makeText(getApplicationContext(), emailid,Toast.LENGTH_SHORT).show();
t1.speak(emailid, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
protected void onDestroy() {
super.onDestroy();
// Don't forget to shutdown tts!
if (mTextToSpeech != null) {
Log.d(TAG, "speach on destroy");
t1.stop();
t1.shutdown();
}
}
I don't understand why didn't you implement your main Activity class from TextToSpeech.OnInitListener...!
Here's your answer:
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AndroidTextToSpeechActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tts = new TextToSpeech(this, this);
btnSpeak = (Button) findViewById(R.id.btnSpeak);
txtText = (EditText) findViewById(R.id.txtText);
// button on click event
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
speakOut();
}
});
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
btnSpeak.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
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?