Connection between PHP (server) and Android (client) Using HTTP and JSON

The main reason for taking a scripting language like PHP is because of the interaction with databases it can offer. In this tutorial I will show you how to use PHP and the MySQL database to retrieve information from the server. For making connection to PHP script, we will  use HTTP protocol from the android system. To implement this tutorial you should have basic knowledge of how to run PHP script and start server.  If we talk about client-server architecture, client is Android device and in server side there is a combination of PHP Script and MySQL. In short, PHP Script sits in middle as shown in image.

Android – PHP – MySQL Scheme

We will use JSON (JavaScript Object Notation) format. JSON is a lightweight text-based open standard designed for human-readable data interchange.

How json will be used in our application.
– When android application will execute, it will connect android device to PHP Script.
– PHP Script will fetch data from the database. It will encode it into json format and send it to the device.
– Now, android application will get these encoded data. It will parse the data and display it on android device.

Here is the implementation detail.
In MySQL create database FOOD. In database create table FOOD. This table consists of two columns. First is FOOD_ID, which is auto_increment and primary_key and having data type INT. Second column is FOOD_NAME, which has data type VARCHAR(20).

We want to retrieve food name from our table FOOD that starts with A.
The PHP code will be very simple:
– Connect to the database
– Run an SQL query, with a WHERE block depending on data from POST/GET values
– Output it in JSON format

For example we will have this functionality in food.php:

<?php
  mysql_connect("127.0.0.1","root","12345");
  mysql_select_db("FOOD");
  $sql=mysql_query("select * from FOOD where FOOD_NAME like 'A%'");
  while($row=mysql_fetch_assoc($sql)) $output[]=$row;
  print(json_encode($output));
  mysql_close();
?>

In our Android application,
– Use a HttpPost to get the data,
– Convert response to string
– Parse JSON data, and use it as you want

The whole code of retrieving data from server to our android application is shown as below.

public class food extends ListActivity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		String result = null;
		InputStream is = null;
		StringBuilder sb=null;
		String result=null;

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://127.0.0.1/food.php");
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}catch(Exception e){
			Log.e("log_tag", "Error in http connection"+e.toString());
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			sb = new StringBuilder();
			sb.append(reader.readLine() + "\n");
			String line="0";

			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}

			is.close();
			result=sb.toString();

		}catch(Exception e){
			Log.e("log_tag", "Error converting result "+e.toString());
		}

		//paring data
		int fd_id;
		String fd_name;
		try{
      	jArray = new JSONArray(result);
      	JSONObject json_data=null;

      	for(int i=0;i<jArray.length();i++){
				json_data = jArray.getJSONObject(i);
				fd_id=json_data.getInt("FOOD_ID");
				fd_name=json_data.getString("FOOD_NAME");
      	}

		}catch(JSONException e1){
			Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();
		}catch (ParseException e1){
			e1.printStackTrace();
		}
	}
}

Another example Using JSON between PHP and Android:

– JSON Code:

JSONObject j = new JSONObject();
j.put("engineer", "me");
j.put("date", "today");
j.put("fuel", "full");
j.put("car", "mine");
j.put("distance", "miles");

– Android code:

String url = "http://www.server.com/phpfile.php";
Map<String, String> kvPairs = new HashMap<String, String>();
kvPairs.put("vehicle", j.toString());
HttpResponse re = HTTPPoster.doPost(url, kvPairs);
String temp = EntityUtils.toString(re.getEntity()); 

if (temp.compareTo("SUCCESS")==0) {
   Toast.makeText(this, "Sending complete!",Toast.LENGTH_LONG).show();
}

– Class code:

public static HttpResponse doPost(String url,Map<String, String> kvPairs) throws ClientProtocolException, IOException{
   HttpClient httpclient = new DefaultHttpClient();
   HttpPost httppost = new HttpPost(url); 

   if (kvPairs != null && kvPairs.isEmpty() == false) {
       List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvPairs.size());
       String k, v;
       Iterator<String> itKeys = kvPairs.keySet().iterator(); 

       while (itKeys.hasNext()) {
              k = itKeys.next();
              v = kvPairs.get(k);
              nameValuePairs.add(new BasicNameValuePair(k, v));
       } 

       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
   } 

   HttpResponse response;
   response = httpclient.execute(httppost); return response;
}

Happy coding 🙂

 

More tutorial, click the link bellow:

The Simplest Way to POST Parameters Between Android and PHP (Android SDK)

Advertisements

2 Comments

  1. help i need a database that can be accessed online in an actual android device how do I do that ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s