6

我花了很长时间才使它起作用,但这显然不是最佳实践。简而言之,当我的 AsyncTask 完成时,我需要显示一个对话框,但是 getApplicationContext() 不起作用,在创建 AsyncTask 时也没有将它作为参数传递。因此,我在 AsyncTask 类中为上下文声明了一个公共变量,并在执行之前对其进行了设置:

    private OnClickListener clickLoadRefs = new OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.d("H","Clicked Load Refs");
        RefreshRefPoints refreshRefPoints = new RefreshRefPoints();
        refreshRefPoints.myCtx=v.getContext();
        refreshRefPoints.execute(v.getContext());
    }
};

private class RefreshRefPoints extends AsyncTask<Context, Integer, Integer> {

    private Integer nPoints=0;
    public Context myCtx;
    private ProgressDialog pd;

    protected Integer doInBackground(Context... ctx) {
        Log.d("H","doInBackground()");
        dbHelper.clearRefPoints();
        requestRefPoints();
        nPoints = parseRefPointsCSV();

        return nPoints;
    }

    protected void onProgressUpdate(Integer... progress) {
    }

    protected void onPreExecute() 
    {
        pd = ProgressDialog.show(myCtx, "Refreshing Reference Points", "Loading...", true,false);
        Log.d( "H", "onPreExecute()" );
    }
    protected void onPostExecute(Integer result) {
        pd.dismiss();
        AlertDialog.Builder builder = new AlertDialog.Builder(myCtx);
        builder.setTitle("Reference points refresh complete");
        builder.setMessage(result+" records loaded");
        builder.setPositiveButton("OK",null);
        builder.show();
        Log.d("H","onPostExecute()");       
    }...etc

任何人都可以告诉我传递上下文的正确方法吗?

谢谢

4

3 回答 3

12

定义一个构造方法并传递上下文一个参数。会更好。

这就是我的意思:

private class RefreshRefPoints extends AsyncTask<Void, Integer, Integer> {

    private Integer nPoints=0;
    private Context myCtx;
    private ProgressDialog pd;

    public RefreshRefPoints(Context ctx){
        // Now set context
        this.myCtx = ctx;
    }

}

就这样。

于 2012-08-31T11:30:56.867 回答
10

您也可以使用YourActivityName.this来指代活动Context。因为 Activites 扩展了 Context,所以这样做是有效的。

于 2012-08-31T11:49:47.903 回答
2

在构造函数中传递上下文为

private OnClickListener clickLoadRefs = new OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.d("H","Clicked Load Refs");
        RefreshRefPoints refreshRefPoints = new RefreshRefPoints(Your_ActivityName.this);
        refreshRefPoints.myCtx=v.getContext();
        refreshRefPoints.execute(v.getContext());
    }
};


private class RefreshRefPoints extends AsyncTask<Void, Integer, Integer> {

    private Integer nPoints=0;
    public Context myCtx;
    private ProgressDialog pd;

public RefreshRefPoints (Context ctx) {
    myCtx = ctx;
}
于 2012-08-31T11:29:17.790 回答