I have PHP webservices and i want to call it throw AsyncTask ..at this stage i have no problem..my problem is that i want to make one class extends AsyncTask and pass to it the uri of the webservices to call it many times in many activities but i don’t know how to do this and call the asynctask .. any help..
Thank you
this is what i have tried to do but it is not working
public class GetNetworkData extends AsyncTask<String, Void, String>{
String uri;
private OnPostExecuteListener mPostExecuteListener = null;
public static interface OnPostExecuteListener
{
void onPostExecute(String result);
}
GetNetworkData(
String Url,
OnPostExecuteListener postExecuteListener) throws Exception {
uri = Url;
mPostExecuteListener = postExecuteListener;
if (mPostExecuteListener == null)
throw new Exception("Param cannot be null.");
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
JSONObject param=null;
String result = null;
HttpClient httpClient = new DefaultHttpClient();
HttpHost httpHost = new HttpHost("192.168.3.111",80);
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
try
{
//HttpEntity bodyEntity = new StringEntity(param.toString(), "utf8");
//httpPost.setEntity(bodyEntity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
result = sb.toString();
instream.close();
}
}
catch (Exception e) {
// TODO: handle exception
}
return result;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if (mPostExecuteListener != null)
{
try {
JSONObject json = new JSONObject(result);
mPostExecuteListener.onPostExecute(result);
} catch (JSONException e){
e.printStackTrace();
}
}
}
}
Create instances of
GetNetworkDataclass wherever and whenever you need. If theUrlandpostExecuteListenerparameters are the same across all the invocations, you could think of a wrapper class that will save these in instance variables and create theGetNetworkDataobjects on demand.The code for using
GetNetworkDatawould be: