My app crashes and in logcat I find the error
android.speech.tts.TextToSpeech.setLanguage(java.util.Locale)' on a null object reference
Here is my class :
public class cl_txt2speech {
TextToSpeech txt2speech;
Activity context;
String txt2speech_current_language = "" ;
boolean txt2speech_available = false ;
//@Override
protected void onCreate(Bundle savedInstanceState) {
txt2speech = new TextToSpeech(context.getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
txt2speech_available = true ;
}
}
});
}
void txt2speech_change_language( String lang )
{
if( lang=="fr" )
{
txt2speech.setLanguage(Locale.FRANCE);
}
else if( lang=="en" )
{
txt2speech.setLanguage(Locale.UK);
}
else if( lang=="es" )
{
Locale locSpanish = new Locale("spa", "MEX");
txt2speech.setLanguage(locSpanish);
}
txt2speech_current_language = lang ;
}
void txt2speech_speak( String lang , String txt )
{
if( lang != txt2speech_current_language ){ txt2speech_change_language( lang ); }
txt2speech.speak(txt, TextToSpeech.QUEUE_FLUSH, null);
}
}
and here is how I use it
cl_txt2speech txt2speech = new cl_txt2speech();
txt2speech.txt2speech_speak( "fr" , "test, 1 2 3" );
I don't understand what is the problem, I defined TextToSpeech txt2speech ; at the beginning.
update 1 : I did add some System.out.println() to trace what is happening, and it seems that the code in onCreate is never executed. So the problem must come from how I use my class.
update 2 :
I ended up moving everything to my fullscreenActivity.java file instead of using a class, to see what happens.
public class FullscreenActivity extends AppCompatActivity implements
TextToSpeech.OnInitListener{
...
public TextToSpeech txt2speech;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
txt2speech = new TextToSpeech(this, this);
...
}
@Override
public void onInit(int status) {
System.out.println( "--------------- onInit() -------------" );
if (status != TextToSpeech.ERROR) {
txt2speech_available = true;
}
}
and onInit is never fired here neither...
Also, when calling txt2speech.getDefaultLanguage() I have the error "getDefaultLanguage failed: not bound to TTS engine"