尝试从静态 AsyncTask 方法显示 ProgressDialog 时出现 NullPointerException

NullPointerException when trying to show ProgressDialog from a Static AsyncTask method

我的 MainActivity 中有一个静态 AsyncTask。我 运行 这个异步任务从 URL 下载数据。我正在尝试显示异步任务的进度对话框,但它在这一行崩溃:private ProgressDialog dialog = new ProgressDialog(mContext);

我将上下文传递给 AsyncTask。

这是我的代码:

private static class MyTasksParse extends AsyncTask<String, String, JSONObject> {
    private Context mContext;
    private ProgressDialog dialog = new ProgressDialog(mContext);

    public MyTasksParse(Context context) {
        mContext = context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        this.dialog.setCanceledOnTouchOutside(false);
        this.dialog.setMessage("Downloading Files... Please Wait...");
        this.dialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args) {
        //get the url and parse it 
        return json;
    }

    @Override
    protected void onPostExecute(JSONObject json) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }

    }
}

我试过将 mContext 转换为 Activity,如下所示: private ProgressDialog dialog = new ProgressDialog(mContext); 但还是一样的错误。

我不确定我做错了什么。如果有人可以帮忙,那就太好了!谢谢:)

初始化ProgressDialogmContextnull。这就是崩溃发生的原因。

您需要更改:

private ProgressDialog dialog = new ProgressDialog(mContext);

至:

private ProgressDialog dialog;

并在onPreExecute中初始化进度对话框:

dialog = new ProgressDialog(mContext);
当你将

mContext 传递给 ProgressDialog 的构造函数时,mContextnull,从而抛出一个 NullPointerException.

这应该有效:

private Context mContext;
private ProgressDialog dialog;

public MyTasksParse(Context context) {
    mContext = context;
    dialog = new ProgressDialog(mContext);
}

因为你有 NullPointerException 因为此时变量 mContext 为空:

    private static class MyTasksParse extends AsyncTask<String, String, JSONObject> {
        private Context mContext;
        private ProgressDialog dialog = new ProgressDialog(mContext);
...
...

这会有所帮助:

private static class MyTasksParse extends AsyncTask<String, String, JSONObject> {
    private Context mContext;
    private ProgressDialog dialog;

    public MyTasksParse(Context context) {
        mContext = context;
        dialog = new ProgressDialog(mContext)
    }

当您在构造函数中收到 context 的值时,您就可以正确地实例化 ProgressDialog =).

您收到 NullPointerException,因为 mContext 为空。 您需要在构造函数中初始化 ProgressDialog,例如

public MyTasksParse(Context context) {
    mContext = context;
    dialog = new ProgressDialog(mContext)
}