How to Connect Android to A Remote Server Using JSON, MySQL and PHP

Operating System

Android-MySQL connectivity using JSON and PHP. INTRODUCTION To connect android app to a remote server, we use a technology called Volley. Before we start the coding, let’s see some basic theory behind the connection process. CONCEPT First the android phone creates a request to the server for asking data. The request contains an address of PHP file. The task of the PHP file is to communicate with the DB and create the list of values in JSON format. There is another advantage of using PHP file that is it gives back-end independence. Back-end independence is nothing but, no matter what front-end coding is used (Android, .NET, Objective C etc…), we no need to change the structure of back-end. The server then creates a response, packs the JSON values in it and passes it back to the android phone. Normally JSON values will be in form of JSON Array. This is because the values might contain more number of rows, so each row is packed in the array. STEPS TO BE FOLLOWED There are four simple steps to be followed to connect MySQL DB to Android. They are 1) Create Request using RequestQueue 2) Create JSONArrayRequest 3) Get JSONObject from JSONArray 4) Add JSONArrayRequest to the request queue EXPLAINATION OF THE STEPS 1) Create request using RequestQueue • Before starting the communication, the front-end (android) should create a connection to the back-end. This connection is created using RequestQueue. • The RequestQueue contains the list of request given by a client, and sends one by one to the server. 2) Create JSONArrayRequest • Once the RequestQueue sends a request to the server, the server starts to process the request and communicates with the DB and created a list of JSON values. • These list of values are packed inside one JSONArray. • The JSONArray is sent to the client. • The client (Android) receives the JSONArray using JSONArrayRequest. 3) Get JSONObject from JSONArray • The JSONArray received from the server contains a list of JSONObject. • In order to process each JSONObject, we have to convert the single JSONArray into list of JSON Objects. • Once the list of JSON Object is obtained, then it is easy to process them. 4) Add JSOnArrayRequest to RequestQueue. • The last and the most important step is to add the JSONArrayRequest into RequestQueue. • If this step is not done, then the Request will never be sent to the server. CODING 1) Create JSONArrayRequest
  1. RequestQueue r; //this line creates a RequestQueue Object.
  2. r= Volley.newRequestQueue(this); //initialize the RequestQueue.
2) Create JSONArrayRequest
  1. String url="http://www.vjenterprisevlr.com/phpfiles/readbooks.php";
  2. JsonArrayRequest jo=new JsonArrayRequest(Request.Method.POST, url, new Response.Listener<JSONArray>() { //this line creates a JSONArrayRequest, it passes the url of the PHP file, and specifies that the passing type is POST.
  3. @Override
  4. public void onResponse(JSONArray response) {
  5. }
  6. }
  7. }, new Response.ErrorListener() {
  8. @Override
  9. public void onErrorResponse(VolleyError error) {
  10.  
  11. }
  12. }
  13. );
3) Get JSONObject from JSONArray
  1. JSONArray books=response;
  2. for(int i=0;i<books.length();i++) //create list of JSONObjects from the JSONArray
  3. {
  4. try {
  5. JSONObject book = books.getJSONObject(i);
  6. String bookname=book.getString("BookName"); // get the bookname from JSONObject
  7. String price=book.getString("Price"); // get price from JSONObject
  8. txt.append(bookname+ "costs " + price+"\n"); //update output
  9. }
  10. catch(Exception e) //handle any exceptions
  11. {
  12.  
  13. }
4) Add JSONArrayRequest to RequestQueue
  1. r.add(jo); //add the request into the queue.
SOURCE CODE
  1. StartPage.java
  2. package tutorials.microfusionsmartsolutions.com.volleytest;
  3.  
  4. import android.os.Bundle;
  5. import android.support.v7.app.AppCompatActivity;
  6. import android.widget.Button;
  7. import android.widget.TextView;
  8.  
  9. import com.android.volley.Request;
  10. import com.android.volley.RequestQueue;
  11. import com.android.volley.Response;
  12. import com.android.volley.VolleyError;
  13. import com.android.volley.toolbox.JsonArrayRequest;
  14. import com.android.volley.toolbox.Volley;
  15.  
  16. import org.json.JSONArray;
  17. import org.json.JSONObject;
  18.  
  19. public class StartPage extends AppCompatActivity {
  20.  
  21. Button but;
  22. TextView txt;
  23. RequestQueue r;
  24.  
  25. @Override
  26. protected void onCreate(Bundle savedInstanceState) {
  27. super.onCreate(savedInstanceState);
  28. setContentView(R.layout.activity_start_page);
  29. but=(Button) findViewById(R.id.button);
  30. txt=(TextView) findViewById(R.id.textView);
  31. String url="http://www.vjenterprisevlr.com/phpfiles/readbooks.php";
  32.  
  33. r= Volley.newRequestQueue(this);
  34.  
  35. JsonArrayRequest jo=new JsonArrayRequest(Request.Method.POST, url, new Response.Listener<JSONArray>() {
  36. @Override
  37. public void onResponse(JSONArray response) {
  38. JSONArray books=response;
  39. for(int i=0;i<books.length();i++)
  40. {
  41. try {
  42. JSONObject book = books.getJSONObject(i);
  43. String bookname=book.getString("BookName");
  44. String price=book.getString("Price");
  45. txt.append(bookname+ "costs " + price+"\n");
  46. }
  47. catch(Exception e)
  48. {
  49.  
  50. }
  51.  
  52. }
  53. }
  54. }, new Response.ErrorListener() {
  55. @Override
  56. public void onErrorResponse(VolleyError error) {
  57.  
  58. }
  59. }
  60. );
  61. r.add(jo);
  62. }
  63. }
XML Layout
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:paddingBottom="@dimen/activity_vertical_margin"
  7. android:paddingLeft="@dimen/activity_horizontal_margin"
  8. android:paddingRight="@dimen/activity_horizontal_margin"
  9. android:paddingTop="@dimen/activity_vertical_margin"
  10. tools:context="tutorials.microfusionsmartsolutions.com.volleytest.StartPage">
  11.  
  12.  
  13. <Button
  14. android:layout_width="wrap_content"
  15. android:layout_height="wrap_content"
  16. android:text="GET"
  17. android:id="@+id/button"
  18. android:layout_alignParentTop="true"
  19. android:layout_centerHorizontal="true" />
  20.  
  21. <TextView
  22. android:layout_width="wrap_content"
  23. android:layout_height="wrap_content"
  24. android:text=""
  25. android:id="@+id/textView"
  26. android:layout_below="@+id/button"
  27. android:layout_marginTop="10dp"
  28. android:textSize="25dp"
  29. android:layout_alignParentEnd="true"
  30. android:layout_alignParentBottom="true"
  31. android:layout_alignParentStart="true" />
  32. </RelativeLayout>

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Submitted byolayemi (not verified)on Tue, 12/13/2016 - 17:39

where is the php code and the connection to database

Add new comment