We are going see how to make a very simple Android app (in our case, a product inventory app) that will call a PHP script to perform basic CRUD(Create, Read, Update, Delete) operations. To brief you on the architecture, this is how it works. First your android app calls a PHP script in order to perform a data operation, lets say “create”. The PHP script then connects to your MySQL database to perform the operation.
So the data flows from your Android app to PHP script then finally is stored in your MySQL database. Allright, lets dig deeper.
Please note that the purpose of the code that I have provided here is to, ease you (beginner level) into connecting an Android app with PHP, MYSQL. You should not take this as a standard or secure coding practice. In production environment, you ideally need to avoid any code that will potentially inject vulnerabilities (like MYSQL Injection). MySQL injection itself is a huge topic and cannot be covered in this single post and that is not the agenda of this post either.
1. What is WAMP Server
WAMP is acronym for Windows, Apache, MySQL and PHP, Perl, Python. WAMP software is one click installer which creates an environment for developing PHP, MySQL web application. By installing this software you will be installing Apache, MySQL and PHP. Alternatively you can use XAMP Server also.
2. Installing and Running WAMP Server
Download & Install WAMP server from www.wampserver.com/en/. Once you have installed wamp server, launch the program from Start -> All Programs -> WampServer -> StartWampServer.
You can test your server by opening the address http://localhost/ in your browser.
Also you can check phpmyadmin by opening http://localhost/phpmyadmin
Following is a screen cast of Downloading and Installing WAMP Server.
3. Creating and Running PHP Project
Now you have the environment ready to develop a PHP & MySQL project. Go to the location where you installed WAMP server (In my case i installed in C:\wamp\) and go to www folder and create a new folder for your project. You have to place all your project files inside this folder.
Create a folder called android_connect and create a new php file called test.php and try out simple php code. After placing following code try to open http://localhost/android_connect/test.php and you should see a message called “Welcome, I am connecting Android to PHP, MySQL“.
Following is a screen cast of Creating and Running a simple PHP project.
4. Creating MySQL Database and Tables
In this tutorial i am creating a simple database with one table. Through out this tutorial i am using same table to perform example operations. Now open phpmyadmin by opening the address http://localhost/phpmyadmin/ in your browser. You can use the PhpMyAdmin tool to create a database and a table.
I am creating a database named androidhive and a table called products.
Following is a screen cast of Creating database and tables in phpmyadmin
5. Connecting to MySQL database using PHP
Now the actual server side coding starts. Create a PHP class to connect to MySQL database. The main purpose of this class is to open a connection to database and close the connection whenever its not needed. So create two files called db_config.php and db_connect.php
db_config.php – will have database connection variables
db_connect.php – a class file to connect to database
Following is code for two php files
Usage: When ever you want to connect to MySQL database and do some operations use the db_connect.php class like this
6. Basic MySQL CRUD Operations using PHP
In this tutorial i am covering basic CRUD (Create, Read, Update, Delete) operations on MySQL database using PHP.
If you are a novice about PHP and MySQL i suggest, you to learn basic PHP and SQL here.
6.a) Creating a row in MySQL (Creating a new product row)
In your PHP project create a new php file called create_product.php and place the following code. This file is mainly for creating a new product in products table.
In the following code i am reading product data via POST and storing them in products table. At the end i am echoing appropriate JSON as response.
For the above code JSON response will be like
When POST param(s) is missing
When product is successfully created
When error occurred while inserting data
6.b) Reading a Row from MySQL (Reading product details)
Create a new php file called get_product_details.php and write the following code. This file will get single product details by taking product id (pid) as post parameter.
The json response for the above file will be
When successfully getting product details
When no product found with matched pid
6.c) Reading All Rows from MySQL (Reading all products)
We need a json to list all the products on android device. So create a new php file named get_all_products.php and write following code.
And the JSON response for above code
Listing all Products
When products not found
6.d) Updating a Row in MySQL (Updating product details)
Create a php file named update_product.php to update product details. Each product is identified by pid.
The json reponse of above code, when product is updated successfully
6.e) Deleting a Row in MySQL (Deleting a product)
The last operation is deletion on database. Create a new php file called delete_product.php and paste the following code. The main functionality of this file is to delete a product from database.
When product successfully deleted
When product not found
Until now, we built a simple api for our products table. We are now done with the server side coding (PHP) and its time to take a break and start our actual android application coding.
7. Creating Android Application
Create a new project in your Eclipse IDE by filling the required details.
1. Create new project in Eclipse IDE by going to File ⇒ New ⇒ Android Project and name the Activity class name as MainScreenActivity.
2. Open your AndroidManifest.xml file and add following code. First i am adding all the classes i am creating to manifest file. Also i am adding INTERNET Connect permission.
3. Now create a new xml file under res ⇒ layout folder and name it as main_screen.xml This layout file contains two simple buttons to view all products and add a new product.
4. Open you main activity class which is MainScreenActivity.java and write click events for two button which are mentioned in main_screen.xml layout.
Displaying All Products in ListView (Read)
5. Now we need an Activity display all the products in list view format. As we know list view needs two xml files, one for listview and other is for single list row. Create two xml files under res ⇒ layout folder and name it as all_products.xml and list_item.xml
6. Create a new class file and name it as AllProductsActivity.java. In the following code
-> First a request is send to get_all_products.php file using a Background Async task thread.
-> After getting JSON from get_all_products.php, i parsed it and displayed in a listview.
-> If there are no products found AddNewProductAcivity is launched.
Adding a New Product (Write)
7. Create a new view and acivity to add a new product into mysql database. Create a simple form which contains EditText for product name, price and description.
Create a new xml file and name it as add_product.xml and paste the following code to create a simple form.
8. Now create new Activity to insert a new product into mysql database. Create a class file and name it as NewProductActivity.java and type the following code. In the following code
-> First new product data is read from the EditText form and formatted into a basic params.
-> A request is made to create_product.php to create a new product through HTTP post.
-> After getting json response from create_product.php, If success bit is 1 then list view is refreshed with newly added product.
Reading, Updating and Deleting a Single Product
9. If you notice the AllProductsActivity.java, In listview i am launching EditProductAcivity.java once a single list item is selected. So create xml file called edit_product.xml and create a form which is same as create_product.xml.
10. Create a class file for edit_product.xml and name it as EditProductActivity.java and fill it with following code. In the following code
-> First product id (pid) is read from the intent which is sent from listview.
-> A request is made to get_product_details.php and after getting product details in json format, I parsed the json and displayed in EditText.
-> After displaying product data in the form if user clicks on Save Changes Button, another HTTP request is made to update_product.php to store updated product data.
-> If the user selected Delete Product Button, HTTP request is made to delete_product.php and product is deleted from mysql database, and listview is refreshed with new product list.
JSON Parser Class
I used a JSON Parser class to get JSON from URL. This class supports two http request methods GET and POST to get json from url.
Run your project and test the application. You might get lot of errors. Always use Log Cat to debug your application, and if you couldn’t solve your errors please do comment here.