In Android, if a TextToSpeech instance fails to initialize (the callback invoked indicating the completion of the TextToSpeech engine initialization returns TextToSpeech.ERROR), does that mean that subsequent attempted method calls to that instance will result in null pointer exceptions?
Example...
We initialize the object:
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.ERROR) {
Log.i("XXX", "There was an error initializing the TTS");
}
}
});
... let's say the init fails, but we then go on to do something like:
t1.speak("hello");
Will this crash... or just say nothing? The reason I ask is that if it does crash, then obviously I would have to put null checks everywhere.
Also, the reason I can't just find out for myself is that I don't know how to simulate the error.
Thanks for any prior knowledge.
For your main question read the docs of the speak()
method (here):
This method is asynchronous, i.e. the method just adds the request to the queue of TTS requests and then returns.
So unless your tts
instance is null
, it shouldn't throw any exception or crash the app, but just return the error code.
Also, the reason I can't just find out for myself is that I don't know how to simulate the error.
Try to use constructor (see docs) that expects as third parameter String engine
and put invalid package name there. It should probably result in error then. (or disable/uninstall all TTS engines on your device/emulator)
Important thing to note regarding constructor is:
In a case of a failure the listener may be called immediately, before TextToSpeech instance is fully constructed.
So unless the status is SUCCESS
, you shouldn't touch your tts
in the listener (of course you can use the tts
afterwards as in your example) because it might not even be assigned / initialized yet.