【问题标题】:Null when passing the context传递上下文时为空
【发布时间】: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”?有必要吗?

标签: java android


【解决方案1】:

我需要做的是将我的 Dialog 类的 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 类中,我已将 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();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多