繁体   English   中英

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

[英]TextToSpeech Null Pointer Exception with 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) {

    }
}

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

TextToSpeech ttsVoice = new TextToSpeech(context, this);

不更新成员,而是更新局部变量。

避免将其在构造函​​数中传递给其他类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM