1

我正在将 ProgressDialogue 与 AsyncTask 一起使用,但正在发生 NullPointerException。

代码

public class MainActivity extends Activity {

    //private MyProgressDialog dialog;
    @Override
    public void onCreate(Bundle icicle) {

        super.onCreate(icicle);

        setContentView(R.layout.activity_main);

        new ProgressTask(MainActivity.this).execute();
   }


  /**
 * this class performs all the work, shows dialog before the work and dismiss it after
 */
public class ProgressTask extends AsyncTask<String, Void, Boolean> {

    private Activity context;

    public ProgressTask(Activity mainActivity) {
        this.activity = mainActivity;
        dialog = new ProgressDialog(context);
    }

    /** progress dialog to show user that the backup is processing. */
    private ProgressDialog dialog;
    /** application context. */
    private Activity activity;

    protected void onPreExecute() {
        this.dialog.setMessage("Progress start");
        this.dialog.show();
    }

        @Override
    protected void onPostExecute(final Boolean success) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
 }

    protected Boolean doInBackground(final String... args) {
       try{    

          return true;
       } catch (Exception e){
          Log.e("tag", "error", e);
          return false;
       }
    }
}
}
4

2 回答 2

3

context你传递给ProgressDialogis null。传递activity在构造函数中初始化的变量。希望这可以帮助。

于 2013-01-18T08:37:39.770 回答
1

试试这个,

public ProgressTask(Activity mainActivity) {
    this.activity = mainActivity;
    dialog = new ProgressDialog(activity); }

实际上在这里, dialog = new ProgressDialog(context);上下文还没有被你初始化。由于它为空,因此它为您提供了 NPE。

所以要么初始化它,要么也尝试以下选项之一,

dialog = new ProgressDialog(mainActivity);
于 2013-01-18T08:37:00.510 回答