【发布时间】:2021-04-11 23:33:53
【问题描述】:
在我的对话框中,我有一个可以单击的按钮(类:Dialog)。单击该按钮后,将调用方法customTts()(在MainActivity 类中):
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void CustomTts(String input) throws Exception {
Tts tts = new Tts(MainActivity.this, _mediaPlayer, barTop, barBottom);
tts.say("Hello!");
}
我得到的错误是:
W/System.err: java.lang.NullPointerException: 尝试调用 虚拟方法'android.content.res.Resources android.content.Context.getResources()' 在空对象引用上
Tts() 的第一个参数需要Context。所以看起来MainActivity.this 返回 null。
public class Tts extends MainActivity {
public Context context;
private final MediaPlayer _mediaPlayer;
private CopyBarVisualizer _barTop;
private CopyBarVisualizer _barBottom;
public Tts(Context context, MediaPlayer _mediaPlayer, BarVisualizer _barTop, BarVisualizer _barBottom) {
this.context = context;
this._mediaPlayer = _mediaPlayer;
this._barTop = (CopyBarVisualizer) _barTop;
this._barBottom = (CopyBarVisualizer) _barBottom;
}
@SuppressLint({"NewApi", "ResourceType", "UseCompatLoadingForColorStateLists"})
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void say(String text) throws Exception {
InputStream stream = context.getResources().openRawResource(R.raw.credential); // R.raw.credential is credential.json
GoogleCredentials credentials = GoogleCredentials.fromStream(stream);
TextToSpeechSettings textToSpeechSettings =
TextToSpeechSettings.newBuilder()
.setCredentialsProvider(
FixedCredentialsProvider.create(credentials)
).build();
在这种情况下如何传递上下文?
【问题讨论】:
-
您能否说明您从哪里调用它以及发生 NPE 的位置?
-
这很奇怪,但请尝试使用
getApplicationContext() -
@Zain 这似乎是一种忽略真正问题的解决方法。
-
@HenryTwist 是的 .. 我们需要查看更多代码
-
为什么“Tts 扩展 MainActivity”?有必要吗?