Passing Parameters In Httpasynctask().execute()
My android app posts a string to web server using json and Http post and following code structure is used, but i want to pass few parameters to AsyncTask<> class through Htt
Solution 1:
Write parameterised constructor for your HttpAsyncTask class. Add private field which you want to use in your HttpAsyncTask class. Then just instantiate the HttpAsyncTask class object with required parameters.
Your class structure would like:
publicclassHttpAsyncTaskextendsAsyncTask<String, Void, String> {
privateString url,reqTimeout,data,text,value;
publicHttpAsyncTask(String url,String reqTimeout,String data, String text, String value){
this.url = url;
this.reqTimeout = reqTimeout;
this.data = data;
this.text = text;
this.value = value;
}
@OverrideprotectedStringdoInBackground(String... params) {
// TODO Auto-generated method stubreturnPOST(params[0]);
}
// onPostExecute displays the results of the AsyncTask.@OverrideprotectedvoidonPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
privateStringPOST(final String url, final String postData,String text, String value) {
// TODO Auto-generated method stubInputStream inputStream ;
String result = "";
try {
// 1. create HttpClientHttpClient httpclient = newDefaultHttpClient();
// 2. make POST request to the given URLHttpPost httpPost = newHttpPost(url);
MainActivity.this.runOnUiThread(newRunnable() {
publicvoidrun() {
Toast.makeText(getApplicationContext(), "2. url is "+url,
Toast.LENGTH_LONG).show();
}
});
String json=postData ;
// 5. set json to StringEntityStringEntity se = newStringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// HttpConnectionParams.setConnectionTimeout(null, 300000);// 7. Set some headers to inform server about the type of the content // httpPost.setHeader("Accept", "application/json");
httpPost.setHeader(text, value);
// 8. Execute POST request to the given URLHttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to stringif(inputStream != null){
result = convertInputStreamToString(inputStream);
}
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return resultreturn result;
}
And then when you call the execute method of HttpAsyncTask class, you should call it in following way:
HttpAsyncTask httpAsyncTask = new HttpAsyncTask(url,reqTimeout,data, text,value); httpAsyncTask().execute(urlStr);
Post a Comment for "Passing Parameters In Httpasynctask().execute()"