Introduction

This article explains how to send employee information to the local server in Android.
This application will show you how to send information to the server in Android. First you need a local server; I used WampServer. You can use Wamp or Xamp, whatever you like to use. I have posted an article on how to set up a WampServer on your Desktop.
Here I will show you how to create a database in WampServer.
Step 1
Open Wampserver on your browser by writing localhost or localhost:8080. In your browser, a page will be displayed.
WampServerPage
Step 2
Click on "PhPmyadmin" on the left side.
PhPmyadmin
Step 3
Click the Databases on the top of the page.
ClickDatabase
Step 4
Click on the SQL on the right side of Databases.
ClickSql
Step 5
Here you will create the database by writing a SQL query and click on the "Go" button. Your database will be created and you can see your database name on the left side of the page.
CreateDatabase
Step 6
Now click on your database name; another page will be shown. Now again click SQL and write a query to create a table in your database.
CreateTable
Now for the coding part.
Step 7
Create PHP files to connect with the server.
db_connect.php
  1. <?php
  2. /**
  3. * A class file to connect to database
  4. */
  5. class DB_CONNECT
  6. {
  7. // constructor
  8. function __construct()
  9. {
  10. // connecting to database
  11. $this->connect();
  12. }
  13. // destructor
  14. function __destruct()
  15. {
  16. // closing db connection
  17. $this->close();
  18. }
  19. /**
  20. * Function to connect with database
  21. */
  22. function connect()
  23. {
  24. // import database connection variables
  25. require_once __DIR__ . '/db_config.php';
  26. // Connecting to mysql database
  27. $con = mysql_connect(DB_SERVER, DB_USER, DB_WORD) or die(mysql_error());
  28. // Selecing database
  29. $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
  30. // returing connection cursor
  31. return $con;
  32. }
  33. /**
  34. * Function to close db connection
  35. */
  36. function close()
  37. {
  38. // closing db connection
  39. mysql_close();
  40. }
  41. }
  42. ?>
db_config.php
  1. <?php
  2. /*
  3. * All database connection variables
  4. */
  5. define('DB_USER', "root"); // db user
  6. define('DB_WORD', ""); // db word (mention your db word here)
  7. define('DB_DATABASE', "employee"); // database name
  8. define('DB_SERVER', "localhost"); // db server
  9. ?>
Create a PHP file to store information on the server.
  1. <?php
  2. /*
  3. * Following code will create a new product row
  4. * All product details are read from HTTP Post Request
  5. */
  6. // array for JSON response
  7. $response = array();
  8. // check for required fields
  9. if (isset($_POST['id']) && isset($_POST['name'])) {
  10. $id = $_POST['id'];
  11. $name = $_POST['name'];
  12. // include db connect class
  13. require_once __DIR__ . '/db_connect.php';
  14. // connecting to db
  15. $db = new DB_CONNECT();
  16. // mysql inserting a new row
  17. $result = mysql_query("INSERT INTO employe_data(id, name) VALUES('$id', '$name')");
  18. // check if row inserted or not
  19. if ($result) {
  20. // successfully inserted into database
  21. $response["success"] = 1;
  22. $response["message"] = "Product successfully created.";
  23. // echoing JSON response
  24. echo json_encode($response);
  25. } else {
  26. // failed to insert row
  27. $response["success"] = 0;
  28. $response["message"] = "Oops! An error occurred.";
  29. // echoing JSON response
  30. echo json_encode($response);
  31. }
  32. } else {
  33. // required field is missing
  34. $response["success"] = 0;
  35. $response["message"] = "Required field(s) is missing";
  36. // echoing JSON response
  37. echo json_encode($response);
  38. }
  39. ?>
Step 8
Create an XML file and write this. In this XML file, you will use two text views, two edittexts, and a button.
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical" >
  6. <!-- Name Label -->
  7. <TextView android:layout_width="fill_parent"
  8. android:layout_height="wrap_content"
  9. android:text="Employee_Id"
  10. android:paddingLeft="10dip"
  11. android:paddingRight="10dip"
  12. android:paddingTop="10dip"
  13. android:textSize="17dip"/>
  14. <!-- Input Name -->
  15. <EditText android:id="@+id/inputId"
  16. android:layout_width="fill_parent"
  17. android:layout_height="wrap_content"
  18. android:layout_margin="5dip"
  19. android:layout_marginBottom="15dip"
  20. android:singleLine="true"/>
  21. <!-- Price Label -->
  22. <TextView android:layout_width="fill_parent"
  23. android:layout_height="wrap_content"
  24. android:text="Employee_Name"
  25. android:paddingLeft="10dip"
  26. android:paddingRight="10dip"
  27. android:paddingTop="10dip"
  28. android:textSize="17dip"/>
  29. <!-- Input Price -->
  30. <EditText android:id="@+id/inputName"
  31. android:layout_width="fill_parent"
  32. android:layout_height="wrap_content"
  33. android:layout_margin="5dip"
  34. android:layout_marginBottom="15dip"
  35. android:singleLine="true"
  36. />
  37. <!-- Description Label -->
  38. <!-- Button Create Product -->
  39. <Button android:id="@+id/btnCreateProduct"
  40. android:layout_width="fill_parent"
  41. android:layout_height="wrap_content"
  42. android:text="Create "/>
  43. </LinearLayout>
Step 9
Create a Java class file MainActivity with the following:
  1. package com.example.adddatatotheserver;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import org.apache.http.NameValuePair;
  6. import org.apache.http.message.BasicNameValuePair;
  7. import org.json.JSONArray;
  8. import org.json.JSONException;
  9. import org.json.JSONObject;
  10. import android.app.Activity;
  11. import android.app.ListActivity;
  12. import android.app.ProgressDialog;
  13. import android.content.Intent;
  14. import android.os.AsyncTask;
  15. import android.os.Bundle;
  16. import android.util.Log;
  17. import android.view.View;
  18. import android.view.View.OnClickListener;
  19. import android.view.inputmethod.EditorInfo;
  20. import android.widget.AdapterView;
  21. import android.widget.AdapterView.OnItemClickListener;
  22. import android.widget.Button;
  23. import android.widget.EditText;
  24. import android.widget.ListAdapter;
  25. import android.widget.ListView;
  26. import android.widget.SimpleAdapter;
  27. import android.widget.TextView;
  28. public class MainActivity extends Activity
  29. {
  30. // Progress Dialog
  31. private ProgressDialog pDialog;
  32. // Create the object of JsonParser class
  33. JSONParser jParser = new JSONParser();
  34. EditText inputName;
  35. EditText inputId;
  36. // url to create send data. This contains the ip address of my machine on which the local server is running. You will write the IP address of your machine
  37. private static String url = "http://192.168.1.135:8080/connect_php/create_product.php";
  38. // JSON Node names
  39. private static final String TAG_SUCCESS = "success";
  40. @Override
  41. public void onCreate(Bundle savedInstanceState)
  42. {
  43. super.onCreate(savedInstanceState);
  44. setContentView(R.layout.activity_main);
  45. // Edit Text
  46. inputName = (EditText) findViewById(R.id.inputName);
  47. inputId = (EditText) findViewById(R.id.inputId);
  48. // Create button
  49. Button btnCreateProduct = (Button) findViewById(R.id.btnSend);
  50. // button click event
  51. btnCreateProduct.setOnClickListener(new View.OnClickListener()
  52. {
  53. /*on button click you will call the execute() method with the object of CreateNewId class and onPreExecute() will be called where we start the progress dialogue. After the execution of
  54. onPreExecute(), doInBackGround method will be called automatically which sends the data to the JsonParser class. In JsonParser class I have created the Http Client to send the data to the server. */
  55. @Override
  56. public void onClick(View view)
  57. {
  58. // creating new product in background thread
  59. new CreateNewId().execute();
  60. }
  61. });
  62. }
  63. /**
  64. * Background Async Task to Create new product
  65. * */
  66. class CreateNewId extends AsyncTask < String, String, String >
  67. {
  68. /**
  69. * Before starting background thread Show Progress Dialog
  70. * */
  71. @SuppressWarnings("unused")
  72. @Override
  73. protected void onPreExecute()
  74. {
  75. super.onPreExecute();
  76. pDialog = new ProgressDialog(MainActivity.this);
  77. pDialog.setMessage("Creating Data..");
  78. pDialog.setIndeterminate(false);
  79. pDialog.setCancelable(true);
  80. pDialog.show();
  81. }
  82. /**
  83. * Creating product
  84. * */
  85. protected String doInBackground(String...args)
  86. {
  87. String name = inputName.getText().toString();
  88. String id = inputId.getText().toString();
  89. // Building Parameters
  90. List < NameValuePair > params = new ArrayList < NameValuePair > ();
  91. params.add(new BasicNameValuePair("name", name));
  92. params.add(new BasicNameValuePair("id", id));
  93. // getting JSON Object
  94. // Note that create product url accepts POST method
  95. JSONObject json = jParser.makeHttpRequest(url,
  96. "POST", params);
  97. // check log cat fro response
  98. Log.d("Create Response", json.toString());
  99. // check for success tag
  100. try
  101. {
  102. int success = json.getInt(TAG_SUCCESS);
  103. if (success == 1)
  104. {
  105. // successfully created product
  106. // Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
  107. //startActivity(i);
  108. finish();
  109. // closing this screen
  110. }
  111. else
  112. {
  113. // failed to create product
  114. }
  115. }
  116. catch (JSONException e)
  117. {
  118. e.printStackTrace();
  119. }
  120. return null;
  121. }
  122. /**
  123. * After completing background task Dismiss the progress dialog
  124. * **/
  125. protected void onPostExecute(String file_url)
  126. {
  127. // dismiss the dialog once done
  128. pDialog.dismiss();
  129. }
  130. }
  131. }
Step 10
Create another Java class file JsonParser with the following:
  1. package com.example.adddatatotheserver;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.io.UnsupportedEncodingException;
  7. import java.util.List;
  8. import org.apache.http.HttpEntity;
  9. import org.apache.http.HttpResponse;
  10. import org.apache.http.NameValuePair;
  11. import org.apache.http.client.ClientProtocolException;
  12. import org.apache.http.client.entity.UrlEncodedFormEntity;
  13. import org.apache.http.client.methods.HttpGet;
  14. import org.apache.http.client.methods.HttpPost;
  15. import org.apache.http.client.utils.URLEncodedUtils;
  16. import org.apache.http.impl.client.DefaultHttpClient;
  17. import org.json.JSONException;
  18. import org.json.JSONObject;
  19. import android.util.Log;
  20. public class JSONParser
  21. {
  22. static InputStream inputStream = null;
  23. static JSONObject jObject = null;
  24. static String jsonString = "";
  25. // constructor
  26. public JSONParser()
  27. {
  28. }
  29. // function get json from url
  30. // by making HTTP POST or GET mehtod
  31. public JSONObject makeHttpRequest(String url, String method, List < NameValuePair > params)
  32. {
  33. // Making HTTP request
  34. try
  35. {
  36. // check for request method
  37. if (method == "POST")
  38. {
  39. // request method is POST
  40. // defaultHttpClient
  41. DefaultHttpClient client = new DefaultHttpClient();
  42. HttpPost post = new HttpPost(url);
  43. post.setEntity(new UrlEncodedFormEntity(params));
  44. HttpResponse httpResponse = client.execute(post);
  45. HttpEntity entity = httpResponse.getEntity();
  46. inputStream = entity.getContent();
  47. }
  48. else if (method == "GET")
  49. {
  50. // request method is GET
  51. DefaultHttpClient httpClient = new DefaultHttpClient();
  52. String paramString = URLEncodedUtils.format(params, "utf-8");
  53. url += "?" + paramString;
  54. HttpGet httpGet = new HttpGet(url);
  55. HttpResponse httpResponse = httpClient.execute(httpGet);
  56. HttpEntity httpEntity = httpResponse.getEntity();
  57. inputStream = httpEntity.getContent();
  58. }
  59. }
  60. catch (UnsupportedEncodingException e)
  61. {
  62. e.printStackTrace();
  63. }
  64. catch (ClientProtocolException e)
  65. {
  66. e.printStackTrace();
  67. }
  68. catch (IOException e)
  69. {
  70. e.printStackTrace();
  71. }
  72. try
  73. {
  74. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
  75. inputStream, "iso-8859-1"), 8);
  76. StringBuilder stringBuilder = new StringBuilder();
  77. String line = null;
  78. while ((line = bufferedReader.readLine()) != null)
  79. {
  80. stringBuilder.append(line + "\n");
  81. }
  82. inputStream.close();
  83. jsonString = stringBuilder.toString();
  84. }
  85. catch (Exception e)
  86. {
  87. Log.e("Buffer Error", "Error converting result " + e.toString());
  88. }
  89. Log.d("debug", "string: " + jsonString);
  90. // try parse the string to a JSON object
  91. try
  92. {
  93. jObject = new JSONObject(jsonString);
  94. }
  95. catch (JSONException e)
  96. {
  97. Log.e("JSON Parser", "Error parsing data " + e.toString());
  98. }
  99. // return JSON String
  100. return jObject;
  101. }
  102. }
Step 11
Android Manifest.Xml file
In the Android Manifest.xml file give the internet permission as in the following:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.example.adddatatotheserver"
  4. android:versionCode="1"
  5. android:versionName="1.0" >
  6. <uses-sdk
  7. android:minSdkVersion="8"
  8. android:targetSdkVersion="18" />
  9. <application
  10. android:allowBackup="true"
  11. android:icon="@drawable/ic_launcher"
  12. android:label="@string/app_name"
  13. android:theme="@style/AppTheme" >
  14. <activity
  15. android:name="com.example.adddatatotheserver.MainActivity"
  16. android:label="@string/app_name" >
  17. <intent-filter>
  18. <action android:name="android.intent.action.MAIN" />
  19. <category android:name="android.intent.category.LAUNCHER" />
  20. </intent-filter>
  21. </activity>
  22. </application>
  23. <uses-permission android:name="android.permission.INTERNET"></uses-permission>
  24. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  25. </manifest>
Step 12
Enter data to send
SendData
Progress
ShowProgress
Data on the Server