The following is the example to send data to server from android App using AsyncTask:
private class AsyncCustomerTable extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(CategoryActivity.this);
HttpURLConnection conn;
URL url = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage(“\tconnecting…”);
pdLoading.setCancelable(false);
pdLoading.show();
}
@Override
protected String doInBackground(String… params) {
try {
// Enter URL address where your php file resides
url = new URL(“http://www.richyan.com/android/bonsushi/customerTable.php”);
} catch (MalformedURLException e) {
e.printStackTrace();
return “exception”;
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod(“POST”);
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter(“customerID”, params[0])
.appendQueryParameter(“tableID”, params[1])
.appendQueryParameter(“numCustomer”, params[2]);
// .appendQueryParameter(“preTableID”, params[3]);
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, “UTF-8”));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
e1.printStackTrace();
return “exception”;
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return(result.toString());
}else{
return(“false”);
}
} catch (IOException e) {
e.printStackTrace();
return “exception”;
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
if (result.equalsIgnoreCase(“false”)||result.equalsIgnoreCase(“exception”)){
Toast toast = Toast.makeText(CategoryActivity.this, “Internet Connection Problem”, Toast.LENGTH_LONG);
toast.show();
} else {
try{
int custTableID = Integer.parseInt(result);
Globals.getInstance().setCustTableID(custTableID);
int catID = (int)spOrderCat.getSelectedItemId();
startMenuActivity(catID);
}catch (Exception e){
Toast toast = Toast.makeText(CategoryActivity.this, “Database Connection Problem”, Toast.LENGTH_LONG);
toast.show();
}
}
}
}
Data diagram: