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

时间:2015-12-15 16:07:32

标签: android android-asynctask alertdialog progressdialog

我的MainActivity中有一个静态AsyncTask。我运行此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);但仍然是同样的错误。

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

4 个答案:

答案 0 :(得分:3)

由于您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 =)。

答案 1 :(得分:1)

mContext传递给null的构造函数时,ProgressDialogNullPointerException,从而抛出private Context mContext; private ProgressDialog dialog; public MyTasksParse(Context context) { mContext = context; dialog = new ProgressDialog(mContext); }

这应该有效:

r.request.headers

答案 2 :(得分:0)

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

您需要更改:

private ProgressDialog dialog = new ProgressDialog(mContext);

为:

private ProgressDialog dialog;

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

dialog = new ProgressDialog(mContext);

答案 3 :(得分:0)

你得到的是NullPointerException,因为mContext为null。 您需要在

之类的构造函数中初始化ProgressDialog
public MyTasksParse(Context context) {
    mContext = context;
    dialog = new ProgressDialog(mContext)
}