Wednesday, October 30, 2013

Android : Connecting to Server (MySQL using PHP)

To connect you android Application with the server Database MYSQL we will be using PHP files. 

  1. When android application will execute, it will connect android device to PHP Script.
  2. PHP Script will fetch data from the database. It will encode it into json format and send it to the device.
  3. Now, android application will get these encoded data. It will parse the data and display it on android device.


Implementation:

First Create a php file and plce it to server. if you are using a localhost wamp server place this php file to www/folderName/myFile.php.

And then write code like this in that php file.

<?php
mysql_connect("localhost","username","password");
mysql_select_db("DatabaseName");
$sql=mysql_query("select * from TableName where EMP_NAME like 'Zee%'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));// this will print the output in json
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
Following is the code for this:
JSONArray jArray = null; String result = null; StringBuilder sb = null; InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
     HttpClient httpclient = new DefaultHttpClient();
     //Why to use 10.0.2.2
     HttpPost httppost = new HttpPost("http://10.0.2.2/folderName/myFile.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());
        }

String name;
try{
      jArray = new JSONArray(result);
      JSONObject json_data=null;
      for(int i=0;i<jArray.length();i++){
             json_data = jArray.getJSONObject(i);
             ct_name=json_data.getString("NAME");//here "Name" is the column name in database
         }
      }
      catch(JSONException e1){
       Toast.makeText(getBaseContext(), "No Data Found" ,Toast.LENGTH_LONG).show();
      } catch (ParseException e1) {
   e1.printStackTrace();
 }
}

Do not forget to insert following permission in AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

That's All Feel free to comment

No comments:

Post a Comment