Sunday, November 9, 2014

Post Data to Server in Android

Firstly add the following two permissions to the AndroidManifest.xml before the <application>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

As the http post is a long process and cannot run in the main thread of the Android activity, therefore it is necessary to use an AsyncTask, create a private class within the Activity class as belows:


class PostCommandTask extends AsyncTask<String, Integer, Integer> {

 protected Integer doInBackground(String... values) {
   // your click actions go here
   // Create a new HttpClient and Post Header
  HttpClient httpclient = new DefaultHttpClient();
  HttpPost httppost = new HttpPost("http://memecs.org/smarthome/post.php?relay_id=2048");

  try {
   // Add your data
   List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
   nameValuePairs.add(new BasicNameValuePair(values[0]+":State", values[1]));
   httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

   // Execute HTTP Post Request
   HttpResponse response = httpclient.execute(httppost);

  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
  } catch (IOException e) {
   // TODO Auto-generated catch block
  }
  
  return 1;
 }

 protected void onPostExecute(String feed) {
  // TODO: check this.exception 
  // TODO: do something with the feed
 }
}
Now to invoke the http post in a ToggleButton
ToggleButton btnSwitch=(ToggleButton)findViewById(id);
btnSwitch.setOnClickListener(new OnClickListener()
{
 @Override
 public void onClick(View v)
 {
  String state=((ToggleButton)v).isChecked() ? "1" : "0";
  new PostCommandTask().execute(address, state);
 }
});

No comments:

Post a Comment