这是我的代码:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate");
        setContentView(R.layout.list);
        new GetBlockListAsyncTask().execute(BlockListActivity.this);
    }
public void initializeDialog() {
        dialog = ProgressDialog.show(BlockListActivity.this, "", "Loading data. Wait...", true);
        dialog.show();
    }

    public void dismissDialog(){
        dialog.dismiss();
    }


GetBlockListAsyncTask:

 public class GetBlockListAsyncTask extends AsyncTask<Object, Boolean, String>{

private BlockListActivity callerActivity;
private String TAG = "GetBlockListAsyncTask";
private String stringCode = "";

@Override
protected String doInBackground(Object... params) {

    callerActivity = (BlockListActivity)params[0];
    try {
        Log.d(TAG, "Start to sleep");
        Thread.sleep(4000);
        Log.d(TAG, "End sleep");
    } catch (InterruptedException e) {
       e.printStackTrace();
    }
    return null;
}

@Override
protected void onPostExecute(String response) {
    callerActivity.dismissDialog();
}

@Override
protected void onPreExecute() {
    callerActivity.initializeDialog();
}


}

它将显示错误:

'Caused by: java.lang.NullPointerException'
  onPreExecute(GetBlockListAsyncTask.java:101)


我发现一个解决方案是,如果将initializeDialog从AsyncTask中移出,并将其放在new GetBlockListAsyncTask().execute(BlockListActivity.this);中的onCreate行之前,它将起作用。
问题是,如果我想将initializeDialog放在AsyncTask中,如何使其工作。

最佳答案

尝试向您的AsyncTask添加一个公共构造函数,该结构接受Activity Context作为第一个参数:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Create a new AsyncTask with the Activity Context
    AsyncTask task = new GetBlockListAsyncTask(this);

    // Execute the task
    task.execute();
}

public class GetBlockListAsyncTask extends AsyncTask<Object, Boolean, String> {
    private Context activityContext;

    private String TAG = "GetBlockListAsyncTask";
    private String stringCode = "";

    //Constructor
    public GetBlockListAsyncTask(Context c) {
        // Store the activity context
        activityContext = c;
    }

    @Override
    protected String doInBackground(Object... params) {
        try {
            Log.d(TAG, "Start to sleep");
            Thread.sleep(4000);
            Log.d(TAG, "End sleep");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String response) {
        activityContext.dismissDialog();
    }

    @Override
    protected void onPreExecute() {
        activityContext.initializeDialog();
    }
}

09-26 03:26