How to connect Android with PHP

In this tutorial I'm going to develop a very simple app that will call a PHP script using HTTP. In previous tutorials you have learned about -  Java Networking API and Apache HttpClient Library to make simple HTTP connections. So it's time to move on.


Android PHP Connect - How it works?

Prerequisites

Before you start to use this tutorial you should be aware of the basics of PHP and Android.
To complete this tutorial you also need a text editor like- Notepad++ and WampServer (windows) or XAMPP (others).

Please note that I'm using WampServer for this tutorial, alternatively you can also use XAMPP or others.


1. What is WampServer ?

WampServer is a Windows web development environment. It allows you to create web applications with Apache, PHP and MySQL.


2. Installing and Running WampServer

You can download WampServer from www.wampserver.com/en/. To install it just double click on the downloaded file and follow the instructions. 

Once you have installed WampServer, just launch it from Start ⇒ All Programs ⇒ WampServer ⇒ StartWampServer.


3. Creating and Running PHP Project

To create PHP project, just go to the location where you installed WampServer (eg. C:\wamp\) and go to www folder (eg. C:\wamp\www\) and create a new folder- hello_php for your project.

Now open Notepad++ or other text editor you like; Create a new file and save it as index.php inside your project folder (eg C:\wamp\www\hello_php\index.php).

Now paste the following code in index.php file -

<?php
echo "Hello PHP";
?>

Now save it & just open http://localhost/hello_php/  or http://127.0.0.1/hello_php/ in your browser to run your project.


4. Creating Android Application

Create a new Android project in eclipse by going to File ⇒ New Android Project and fill required details:

    Project Name : AndroidPHPConnect
    Package : com.sunil.phpconnect
    Main Activity : MainActivity.java
    Layout : activity_main.xml
    Build Target : Android 2.2

Since you are going to perform network operations, you must need to add INTERNET permission (android.permission.INTERNET) to AndroidManifest.xml file. -

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sunil.phpconnect"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="5"
        android:targetSdkVersion="8" />

    <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.sunil.phpconnect.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>

Now open the res/layout/activity_main.xml file and insert the following code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/tvResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="30dip"
        android:textSize="20sp" />

</RelativeLayout>

Now open the MainActivity.java file and add the following code:

package com.sunil.phpconnect;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

HttpClient httpclient;
HttpGet request;
HttpResponse response;
String url;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// URL of PHP Script

url = "http://10.0.2.2/hello_php/";

// TextView to display result

TextView result = (TextView) findViewById(R.id.tvResult);

// Try to connect using Apache HttpClient Library
try {
httpclient = new DefaultHttpClient();
request = new HttpGet(url);
response = httpclient.execute(request);
}

catch (Exception e) {
// Code to handle exception
}

// response code
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {

// Appending result to textview
result.append(line);
}
} catch (Exception e) {
// Code to handle exception
}
}
}

If you already know about how to make simple HTTP connections in Android, then you can easily understand the above Activity code. One thing you need to keep in mind is that - " always use the localhost address http://10.0.2.2 in place of http://localhost or http://127.0.0.1 in Android ".

Now run your project. (See the screenshot below)

Android PHP



That's it ! You can also download the source code of this tutorial. 

Download Code






2 Comments:

srinivasareddy maram said...

very good tutorial for beginners.It is very use ful to me thank u.

Rakhi Dhavale said...

i was looking for a simple code to connect android to php that would help me,and the CODE IS EASY TO UNDERSTAND !! thanks!

Post a Comment

Recent Posts

Site Stats

Our Apps

Get it on Google Play

©2012-2014 Android Aspect - All rights reserved | Powered by Blogger

Creative Commons License