0

我尝试制作一个 AsyncTask 类以在后台上传可变温度。我如何插入参数?网址,变量?我制作了这段代码,但我有错误......

public class SimpleHttpPut extends AsyncTask<Void, Void, Void> {


@Override
protected Void doInBackground(Void... params) {

//public static void main(String urlt,int t) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(urlt);
    try {
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
      nameValuePairs.add(new BasicNameValuePair("temp",String.valueOf(t)));
      post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

      HttpResponse response = client.execute(post);
      BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
      String line = "";
      while ((line = rd.readLine()) != null) {
        System.out.println(line);
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
 // }
 return null;
}

protected void onPostExecute(Void result) {


    }
4

1 回答 1

3

请参阅我对这个 SO 帖子的回答......它解释了将参数直接传递给doInBackground函数以及 Aynctask 类本身,以及在调用活动中调用回调函数。

在您的情况下,最重要的答案是将参数的字符串数组传递给 doInBackground

在调用活动中:

//params to pass to doInBackground
private String[] params= {"mynamespace", "mymethods", "mysoap", "myuser", "mypass"}; 

//Pass your args array and the current activity to the AsyncTask
new MyTask("my arg1", 10).execute(params);

在异步任务中:

public class MyTask extends AsyncTask<String, Void, String>{
    private String stringArg;
    private int intArg;

    public MyTask(String stringArg, int intArg){
        this.stringArg = stringArg;
        this.intArg = intArg;
    }
    @Override
    protected Void doInBackground(String... params) {
        //These are params local to this function
        String _NAMESPACE = params[0];
        String _METHODNAME = params[1];
        String _SOAPACTION = params[2];
        String _USER_NAME = params[3];
        String _USER_PASS= params[4];

        //intArg & stringArg are now available throughout the class

        //Do background stuff
    }
}
于 2012-12-18T18:31:11.637 回答