2014-10-26 86 views
0

我试图创建一个TextToSpeech管理器类。

我在调用类的构造函数时收到空指针异常错误。

TTS管理类接受单个上下文参数。

MainActivity类别尝试通过调用TextToSpeech空指针异常与上下文

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

stacktrace请 – mapodev 2014-10-26 17:53:43

回答

1

看起来像你通过通过这个新的文字转语音泄漏在它自己的构造函数部分构造TTS_Manger。例如,此时ttsVoice成员将为空。另外:

TextToSpeech ttsVoice = new TextToSpeech(context, this); 

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

避免将此构造函数传递给其他类。