samedi 28 février 2015

How to use Asynchronous and onPostExecute to send value to PHP and get Response



How to send value to php page using Asynchronous with HttpRequest and get a response, then do something with it using OnPostExcute for example.


Java :



private class MyAsyncTask extends AsyncTask<String, Integer, Double>{

@Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}

protected void onPostExecute(Double result){
pb.setVisibility(View.GONE);
// Do something with the response here
// ....
}

public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("__url_to_file.php");

// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);
}

}


PHP :



<?php
// return the value back to the app
echo $_POST["myHttpData"];

?>



Aucun commentaire:

Enregistrer un commentaire