1

AsyncTask で ProgressDialogue を使用していますが、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渡すProgressDialogは ですnullactivityコンストラクターで初期化されている変数を渡します。お役に立てれば。

于 2013-01-18T08:37:39.770 に答える
1

これを試して、

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

実際には dialog = new ProgressDialog(context);、コンテキストはあなたによって初期化されていません。null であるため、NPE が提供されます。

したがって、初期化するか、以下のオプションのいずれかを試してください。

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