[英]Null when passing the context
在我的對話框中,我有一個可以單擊的按鈕(類: 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: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
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();
在這種情況下如何傳遞上下文?
我需要做的是將我的 Dialog class 的getActivity()
傳遞給MainActivity()
。 我能夠使用接口和onAttach()
做到這一點:
public interface OnInputListener {
void customTts(String input, Activity activity);
}
public OnInputListener onInputListener;
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
onInputListener = (OnInputListener) getActivity();
}
catch (ClassCastException e) {
Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage());
}
}
這是我按下按鈕時使用的:
onInputListener.customTts(input, getActivity());
在我的 MainActivity class 中,我將customTts()
方法更改為:
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void customTts(String input, Activity activity) {
Tts tts = new Tts(activity, _mediaPlayer, barTop, barBottom);
try {
tts.say(input);
} catch (Exception e) {
e.printStackTrace();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.