android app and mysql database

How to connect Android app with MySQL database and parse data using JSON and PHP

Today we are going to learn how to connect Android app with MySQL database. We will fetch table data, then parse it as JSON data to an android app. Before we get started, let define these few terms and know what they are.

What is JSON?

JSON standards for Javascript Object Notation.Its a way of storing data and exchanging. Javascript objects can be transformed into JSON and send them to the server.JSON received can also be converted back to Javascript Objects.

JSON can be in two forms. These are

JSON Array

JSON Array is a list of values inside braces. Example

JSON Object

It’s a collection that has Name-Value pairs. Example

NB: We can have a list of JSON objects inside a JSON array.Example below.

Read more about JSON here >>JSON tutorial 

Create Database table using Xampp Server.

Create database college using Xampp Server. You can use Wamp server, Lamp Server whatever you’re comfortable with. Inside the database, create table students.

mysql table structure
MySQL database table

Add data to the table

mysql database table with data

Retrieve table data using PHP and convert to JSON format

Open c:/xampp/htdocs  path.Create a new folder and name it college. Open the folder and create a PHP file and name is getStudents.php.Inside the file add below code.

php script Android App JSON Parsing

It’s now time to tackle the elephant in the room. Steps.

Create an Android Project.

Open Android Studio and create a new project with empty activity.

create android project
creating android project

Create User Interface

We will display fetched students details in a ListView.Create ListView in activity_main.xml 

Fetch JSON string from Wamp Server

There are two ways of fetching JSON string. We can use Emulator or a real device.

Using Emulator

Open the cmd prompt and type ipconfig.

Acessing emulator localhost

Using Real device

Connect your real device and computer using the same wifi. Check your computer IP address and enter below website url in a real device. Localhost should be replaced with your computer IP address.http://localhost/college/getStudents.php.

Java Method and Class to Fetch JSON String.

To fetch JSON string from the server we will use AsyncTask.Below is the code to do the task.

Don’t forget to enable android.permission.INTERNET so that your application will be able to connect to the internet.

android JSON parsing
android JSON parsing

Parse JSON and display results in a ListView method

This is the last part of this tutorial now. It’s time to load our result to a ListView.We are going to create a new method loadListview(String stringJson) which takes in a String variable.

Complete code

android json parsing
Android JSON parsing example

Download Complete Source code here