具有上下文的TextToSpeech Null指针异常

时间:2014-10-26 17:50:52

标签: android pointers null android-context

我正在尝试创建一个TextToSpeech管理器类。

调用类的构造函数时,我收到Null Pointer Exception错误。

TTS管理类接受单个Context参数。

MainActivity类尝试通过调用

来实例化对象
TTS_Manager tts = new TTS_Manager(this);

Logcat显示正在调用的TTS_Manager类的构造函数,然后是NPE:

TextToSpeech ttsVoice = new TextToSpeech(context, this);

我认为上下文的处理方式有问题。

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) {

    }
}

1 个答案:

答案 0 :(得分:1)

通过将此传递给新的TextToSpeech,您似乎在其自身的构造函数中泄漏了部分构造的TTS_Manger。例如,ttsVoice成员此时将为null。也:

TextToSpeech ttsVoice = new TextToSpeech(context, this);

不更新成员,而是更新本地变量。

避免将构造函数中的this传递给其他类。