1

这是我的代码:

@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);in行之前onCreate,它就可以工作。
问题是如果我想将 initializeDialog 放在 AsyncTask 中,如何使它工作。

4

1 回答 1

3

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

@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();
    }
}
于 2012-09-06T04:12:10.237 回答