MainActivity不包含类

时间:2016-03-20 18:59:48

标签: java android

如何解决这个问题?

  

MainActivity.this不是封闭的类。

谢谢

public class uploadToServer extends AsyncTask<Void, Void, String> {

protected void onPreExecute() {
    super.onPreExecute();
    ProgressDialog pd= new ProgressDialog(MainActivity.this); //error is here
    pd.setMessage("Wait image uploading!");
    pd.show();
}
}

1 个答案:

答案 0 :(得分:2)

AsyncTask的构造函数中,传递Context&amp;在需要时使用它

public class uploadToServer extends AsyncTask<Void, Void, String> {
   private Context mContext;
   public uploadToServer (Context context){
        mContext = context;
   }

   protected void  onPreExecute() {
      super.onPreExecute();
      ProgressDialog pd= new ProgressDialog(mContext); //change is here
      pd.setMessage("Wait image uploading!");
      pd.show();
   }
}

MainActivity拨打电话,

uploadToServer task = new uploadToServer(getApplicationContext());
task.execute();