0

I'm attempting to create a TextToSpeech manager class.

I'm getting a Null Pointer Exception error when the class’s constructor is called.

The TTS managing class accepts a single Context parameter.

The MainActivity class attempts to instantiate the object by calling

TTS_Manager tts = new TTS_Manager(this);

Logcat shows the TTS_Manager class’s constructor being called and then the NPE:

TextToSpeech ttsVoice = new TextToSpeech(context, this);

My take is that there is something wrong with the way the context is being handled.

package com.example.TTS01;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;

public class TTS_Manager implements TextToSpeech.OnInitListener{
    TextToSpeech ttsVoice;

    public void TTS_Manager(Context context){
        //Null Pointer Exception thrown on next line
        TextToSpeech ttsVoice = new TextToSpeech(context, this);

        ttsVoice.setOnUtteranceProgressListener(new UtteranceProgressListener() {
            @Override
            public void onStart(String utteranceID) {
                            }

            @Override
            public void onDone(String utteranceID) {
                            }

            @Override
            public void onError(String utteranceID) {
                            }
        });

    }

    @Override
    public void onInit(int i) {

    }
}
0

1 Answer 1

1

Looks like you're leaking a partially constructed TTS_Manger in it's own constructor function by passing this to new TextToSpeech. For example, the ttsVoice member will be null at this time. Also:

TextToSpeech ttsVoice = new TextToSpeech(context, this);

Does not updated the member, but a local variable.

Avoid passing this in the constructor to other classes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.