Android External Database Connection using PHP MySQL

While i was learning Android (Still learning 😉 ), I was always confused and also have some fear how to connect our Application To External Database and how to Access data from our database. Well you don’t worry about this, because this post is gonna help you to connect your database to your Android Application.

Before we start i wanna mention one thing which is very important, you can use this process to learn (Build Concept) and how to connect your application to your database not for Real world Application because here we are allowing network request on our main thread ie. the UI thread (which is a lengthy operation, better way to get around this is to use Asynctask which is a helper class which allows us to execute lengthy operations on a separate thread). i will share more about AsyncTask later on my blog.

Before follow this post make sure

1.You have installed WAMP or LAMP in your system

2.you have installed Android Development Kit in your system properly.

Create a database

Create a database “StudentDatabase” and then create a table “Student” in your localhost server.
In your database you can create any number of column ,here i have created four(‘First Name’, ‘Last Name’, ‘Phone No.’, ‘Email ID’) insert some values in your database so that you can see those values.

Create a PHP File

Create a file getAllStudent.php inside c:/wamp/www/ and save this file inside JSON folder and if your using linux then /var/www/json if you don’t have json then Just make a folder.

getAllStudent.php

<?php
$con = mysql_connect(“localhost”,”root”,”password”);
if(!$con)
{
die(‘Could not Connect: ‘ .mysql_error());
}
mysql_select_db(“StudentDatabase”,$con);
$result=mysql_query(“SELECT * FROM Student”);
while($row = mysql_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
?>

now we are done with MySQL and PHP. Lets Develop our Application.

Source code :

Create a Android project and choose Minimum Required SDK to API14: Android 4.0(IceCreanSandwich) bcoz Strictmode option will work only after this API.

main.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical” >
<TextView
android:id=”@+id/result”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”/>
</LinearLayout>

mainifest.xml

In your manifest.xml file give permission of internet to your application.
Permission->Add->Uses permission->Select android.permission.INTERNET

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
package=”com.anish.externaldatabase”
android:versionCode=”1″
android:versionName=”1.0″ >
<uses-sdk android:minSdkVersion=”8″ android:targetSdkVersion=”17″ />
<uses-permission android:name=”android.permission.INTERNET” />
<application android:allowBackup=”true” android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name” android:theme=”@style/AppTheme” >
<activity android:name=”com.anish.externaldatabase.MainActivity” android:label=”@string/app_name” >
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>
</manifest>

MainActivity.java

package com.anish.externaldatabase;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView resultView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.database);
StrictMode.enableDefaults(); //This will strictly allow to run your main thread
resultView = (TextView) findViewById(R.id.result);
getData();
}

public void getData() {
String result = “”;
InputStream isr = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(“http://localhost/json/getAllStudent.php&#8221;);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
} catch (Exception ex) {
Log.e(“log_tag”, “Error in Http Connection” + ex.toString());
resultView.setText(“Could not connect to Database”);
}

// convert reponse to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(isr, “iso-8859-1”), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + “\n”);
}
isr.close();

result = sb.toString();
} catch (Exception ex) {
Log.e(“log_tag”, “Error Converting Result” + ex.toString());
}

// Parse Json Data
try {
String s = “”;
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = jArray.getJSONObject(i);
s = s + “Name : ” + json.getString(“First Name”) + ” ”
+ json.getString(“Last Name”) + “\n” + “Mobile: ”
+ json.getInt(“Phone No.”) + “\n” + “Email Id: ”
+ json.getString(“Email ID”) + “\n\n”;
}
resultView.setText(s);
} catch (Exception ex) {
Log.e(“log_tag”, “error in Parsing data” + ex.toString());
}
}
}

 

If You Have Any Problem or Suggestion For Me Then Drop Me a Mail. I Will Wait For Your Anticipated Feedback and Suggestion.

Advertisements

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