Friday 7 November 2014

How to Connect Android with PHP, MySQL and JSON – Example

We will create a server application using PHP which will fetch data from mysql database. Then we transform that data into JSON object with the help of PHP. After that we fetch JSON data from android client application. In this way we connect android with php and mysql.
Steps to follow to connect android with php 
  1. Implement Interface class which will help to connect android and php server.
  2. Create Main Activity.
  3. Perform background processing using AsynchTask.
  4.  Create server side code in php to connect to MySQL.

ClientServerInterface.java

Let us create a client server interface class which is used to fetch data from server. We use PHP to create JSON object and we get json data to mobile application.
Explanation:

We connect android with php server. Then we send and retrieve data using HTTPClient. HTTPPost specifies that our request method is post. The response is stored in HTTPResponse‘URL’ is the actual link where JSON is present.
Then we use inputstream to get data into bytes. We need to convert byte-stream to character stream. After that we build String with the help of StringBuilder.

MainActivity.java

Next, we create main activity. We use AsynchTask to enable background processing. Connection between android client application and php server is network intensive so we use another thread to process request instead of main thread.
Server Side Code
Create json array using php and mysql. Get data from database table and transform it to json array.

serverside.php
In this way we get JSON data from server and we connect android with PHP and MYSQL. Feel free to post if you got any errors in your application.

No comments:

Post a Comment