Search code examples
androidlistenertext-to-speech

Trying to call Toaster or Custom function inside setOnUtteranceProgressListener


In my main Fragment, I have implemented TextToSpeech mainFragment extends Fragment implements TextToSpeech.OnInitListener.

The text to speech is working fine, also i have added an UtteranceProgressListener which is working.

My problem : Am unable to call any custom functions eg gotoNextChapter() or even a simple Toaster. getting error Can't create handler inside thread that has not called Looper.prepare()

Any suggestions or solutions welcomed....

My code snippet:

UtteranceProgressListener SpeechListener = new UtteranceProgressListener() {
            @Override
            public void onStart(String utteranceId) {
                Toast.makeText(getActivity(),utteranceId, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onDone(String utteranceId) {
                Toast.makeText(getActivity(),utteranceId, Toast.LENGTH_LONG).show();

                gotoNextChapter(); <====function I want to call
                read_mode = 0;
            }

            @Override
            public void onError(String utteranceId) {
                Toast.makeText(getActivity(),utteranceId, Toast.LENGTH_LONG).show();
            }
        };

Setting the utterance complete listener:

myTTS.setOnUtteranceProgressListener(SpeechListener);

Error am getting:

Caught a RuntimeException from the binder stub implementation.
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
                                                            at
android.os.Handler.<init>(Handler.java:209)
                                                            at
android.os.Handler.<init>(Handler.java:123)
                                                            at
android.widget.Toast$TN.<init>(Toast.java:350)
                                                            at
android.widget.Toast.<init>(Toast.java:106)
                                                            at
android.widget.Toast.makeText(Toast.java:264)
                                                            at com.MainActivity$Read$10.onDone(MainActivity.java:1252)

Solution

  • ok I got a solution, now my question just seems trivial

    my updated code looks like this:

    @Override
    public void onDone(String utteranceId) {
    
    runOnUiThread(new Runnable() {
    
                    public void run() {
                        Toast.makeText(getContext(),utteranceId,Toast.LENGTH_LONG).show();
    gotoNextChapter(); <====function I want to call
    read_mode = 0;
                    }
                });
    }
    

    Thanks to these guyes here: How can I Toast after Text to Speech finish speaking Android and When may we need to use runOnUiThread in android application?