将两个参数传递给asynctask方法。如何?

时间:2012-02-16 15:23:20

标签: android android-asynctask

我正在设计一个经常与Web服务器通信以进行更新的应用程序。通信仅在用户请求时发生。我发现AsyncTask在这里可能会有所帮助。所以我修改了一个类来为我的应用程序提供AsyncTask。

我想将url和http post参数传递给anysc类的doInBackground进程。 我无法弄明白该怎么做。

这是 -

public class GetXMLFromServer extends
    AsyncTask< String, Void, String> {
private Context context;

GetXMLCallback gc = null;

ProgressDialog progressDialog;

public GetXMLFromServer(Context context, GetXMLCallback gc) {
    this.context = context;
    this.gc = gc;
    progressDialog = new ProgressDialog(this.context);
}

protected void onPreExecute() {
    progressDialog.setMessage("Fetching...");
    progressDialog.show();
}

@Override
protected void onPostExecute(String result) {
    gc.onSuccess(result);
    progressDialog.dismiss();
}


 @Override
protected String doInBackground(String... params) {
     String response = "";
    response=CustomHttpClient.executeHttpPost(params[0]);
    return null;
} 
    //Confused how to pass URL and http post parameters to doInBackground().
  }

我有一个接口用于处理从onPostExecute()发送的响应。它就像休耕一样。

   package com.project.main.external;

   public interface GetXMLCallback {
       void onSuccess(String downloadedString);
       void onFailure(Exception exception);
   }

这是我的主要活动,需要http响应 -

 public class UpdateList extends Activity implements GetXMLCallback { 
 //above line also throws error that interface methods are not implemented yet
 //they are (few lines below) defined.

private TextView textView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_layout);
    textView = (TextView) findViewById(R.id.TextView01);
}

GetXMLCallback gc = new GetXMLCallback() {

    public void onFailure(Exception exception) {

    }

    public void onSuccess(String downloadedString) {
        textView.setText(downloadedString);
    }

};

public void getUpdates(View view) {
    GetXMLFromServer task = new GetXMLFromServer(UpdateList.this, gc);
    task.execute(WebConstants.GET_UPDATES);
}
    }

3 个答案:

答案 0 :(得分:10)

AsyncTask已经允许更多参数:
在你的情况下,这样称呼它:

task.execute("parameter_one","parameter_two","parameter_three");

在doInBackground中,你可以使用:

params[0]
params[1]
params[2]

等等

请注意,所有参数必须是相同的Type,在您的情况下为String。

答案 1 :(得分:4)

  1. 您可以向已有的构造函数添加一个或多个内容,并填充AsyncTask的某些成员,然后使用这些成员在doInBackground
  2. 中进行POST
  3. 您可以将其更改为扩展AsyncTask<HttpPost, Void, String>AsyncTask<SOME_CLASS, Void, String>,其中SOME_CLASS是字符串的ArrayList,HashMap或您可以创建的其他类,其中包含构建HttpPost所需的所有内容< / LI>

答案 2 :(得分:0)

public class GetXMLFromServer extends
AsyncTask< String, Void, String> {
private Context context;

GetXMLCallback gc = null;

ProgressDialog progressDialog;

public Type variable1;
public Type variable2;

并设置变量:

GetXMLFromServer task = new GetXMLFromServer(UpdateList.this, gc);
task.variable1 = XXXXX;
task.variable2 = XXXXX;
task.execute(WebConstants.GET_UPDATES);
相关问题