我尝试在后台制作一个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) {
}
答案 0 :(得分:3)
请参阅我对this SO post的回答...它解释了将参数直接传递给doInBackground
函数以及Aynctask类本身,以及在调用活动中调用回调函数。 / p>
在你的情况下,点回答是将一个字符串数组的params传递给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);
在Asynctask中:
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
}
}