Android PHP Read From MySQL DB Using Volley

By | December 14, 2014

In this previous tutorial we have seen how to insert data from native android application into MySQL database using php , here we are going to read all the from database and show it on to list view

Demo Video


Firstly you have to set up php server.
Read : Setting PHP And MYSQL Server

After Inserting Data into MySQL database table myorder ( )

PHP Script

1 a. DBConfig

file : db_config.php

$mysql_hostname = “localhost”;
$mysql_user = “root”;
$mysql_password = “”;
$mysql_database = “orders”;

$db = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die(“Opps some thing went wrong”);
mysql_select_db($mysql_database, $db) or die(“Opps some thing went wrong”);


1 b. Read All Data

Php Script to read data from MySQL database.

file : read_allorder.php


// array for JSON response
$response = array();

// get all items from myorder table
$result = mysql_query(“SELECT *FROM myorder”) or die(mysql_error());

if (mysql_num_rows($result) > 0) {
    $response[“orders”] = array();

    while ($row = mysql_fetch_array($result)) {
            // temp user array
            $item = array();
            $item[“id”] = $row[“id”];
            $item[“item”] = $row[“item”];
            // push ordered items into response array
            array_push($response[“orders”], $item);
      // success
     $response[“success”] = 1;
else {
    // order is empty
      $response[“success”] = 0;
      $response[“message”] = “No Items Found”;
// echoing JSON response
echo json_encode($response);


1 d. API URL Call

Request Type    GET
JSON Output On Success


 On Failure



2 a. Add Network Permission

 <uses-permission android:name=”android.permission.CHANGE_NETWORK_STATE” />
 <uses-permission android:name=”android.permission.INTERNET” />

2 b. Build Project With Volley Library

Add the following lines to the dependencies section in your project’s app:module build.grade file and sync . The Highlighted line syncs Volley library .


dependencies {
    compile fileTree(dir: ‘libs’, include: [‘*.jar’])
    testCompile ‘junit:junit:4.12’
    compile ‘’
    compile ‘’
    compile ‘com.mcxiaoke.volley:library:1.0.19’


2 c. Layout

Create XML Layout

file : list_items.xml

<?xml version=”1.0″ encoding=”utf-8″?>
    android:padding=”10dp” >

        android:textColor=”#000000″ />

        android:textColor=”#000000″ />

        android:src=”@drawable/fwd” />


2 d. Application Object

Create a class MyApplication which extends Application ,this application object represents singleton pattern , the purpose of this class is make volley request available  through out of the application

  • The getInstance method of application class returns application object.
  • The getReqQueue method returns the RequestQueue object.
  • Inside addToReqQueue method we are adding calling add() method upon RequestObject and passing request as paramter to it .
  • The cancelPendingReq is used for cancelling the request.

file :

package com.pavan.androidphp;


public class MyApplication extends Application {

    private RequestQueue mRequestQueue;
    private static MyApplication mInstance;

    public void onCreate() {
        mInstance = this;

    public static synchronized MyApplication getInstance() {
        return mInstance;

    public RequestQueue getReqQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());

        return mRequestQueue;

    public <T> void addToReqQueue(Request<T> req, String tag) {


    public <T> void addToReqQueue(Request<T> req) {


    public void cancelPendingReq(Object tag) {
        if (mRequestQueue != null) {

2 e. Activity

Create a class ReadData and extend this class to ListActivity class and the above defined xml layout is represents layout for items of list view  onclick of read button make JSONObjectRequest and show data into List View .

file :

package com.pavan.androidphp;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class ReadData extends ListActivity {

    String url = “”;
    ArrayList<HashMap<String, String>> Item_List;
    ProgressDialog PD;
    ListAdapter adapter;

    // JSON Node names
    public static final String ITEM_ID = “id”;
    public static final String ITEM_NAME = “item”;

    protected void onCreate(Bundle savedInstanceState) {

        Item_List = new ArrayList<HashMap<String, String>>();

        PD = new ProgressDialog(this);

        getListView().setOnItemClickListener(new ListitemClickListener());


    private void ReadDataFromDB() {;
        JsonObjectRequest jreq = new JsonObjectRequest(Method.GET, url,
                new Response.Listener<JSONObject>() {

                    public void onResponse(JSONObject response) {
                        try {
                            int success = response.getInt(“success”);

                            if (success == 1) {
                                JSONArray ja = response.getJSONArray(“orders”);

                                for (int i = 0; i < ja.length(); i++) {

                                    JSONObject jobj = ja.getJSONObject(i);
                                    HashMap<String, String> item = new HashMap<String, String>();
                                    item.put(ITEM_ID, jobj.getString(ITEM_ID));


                                } // for loop ends

                                String[] from = { ITEM_ID, ITEM_NAME };
                                int[] to = {, };

                                adapter = new SimpleAdapter(
                                        getApplicationContext(), Item_List,
                                        R.layout.list_items, from, to);



                            } // if ends

                        } catch (JSONException e) {

                }, new Response.ErrorListener() {

                    public void onErrorResponse(VolleyError error) {

        // Adding request to request queue


    //On List Item Click move to UpdateDelete Activity
    class ListitemClickListener implements ListView.OnItemClickListener {

        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {

            Intent modify_intent = new Intent(ReadData.this,

            modify_intent.putExtra(“item”, Item_List.get(position));




What Next

Also Check Out The Continued Tutorials On Android PHP MYSQL .

Android PHP CRUD

Android PHP Insert
Android PHP Update
Android PHP Delete
  • help mi…..I get an error on the part (Method.GET, url, null,
    I use the library compile 'com.mcxiaoke.volley:library:1.0.18'

  • when i run the apps, there are 2 error log:Caused by: java.lang.NullPointerException <-MyApplication.getInstance().addToReqQueue(jreq); <-ReadDataFromDB();

  • when i run the apps, there are 2 error log:Caused by: java.lang.NullPointerException <-MyApplication.getInstance().addToReqQueue(jreq); <-ReadDataFromDB();

  • cast null to string
    JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, (String)null,
    new Response.Listener()

  • Hi my friend

    Try to add this line in your manifest file inside application tag such as :

    MyApplication is the class that extends to Application

  • Hi, I was wondering where do you use MyApplication classe ? i used the requestQueue object to send data to my database, but it seems like it works form only one time, when i try to send a sencond request (by clicking a send button) nothing happens

  • Hi! how can i change different image on imageView1 of list_items.xml if i have a different value for item_name? i try with a if(ITEM_NAME.euqals(…){ myImageView.setImageResource(drw…)} but i get error or notihing change. Is it a possible modification for the adapter?

  • How do I add into the picture in the ListView?

  • How do I add extra strings to show in listview? put an extra column in db and change php read_allorder. extra string here: JSONObject jobj = ja.getJSONObject(i);
    HashMap item = new HashMap();
    item.put(ITEM_ID, jobj.getString(ITEM_ID));
    item.put(ITEM_NAME, jobj.getString(ITEM_NAME));
    item.put(ITEM_test, jobj.getString(ITEM_test));
    and here: // JSON Node names
    public static final String ITEM_ID = "id";
    public static final String ITEM_NAME = "item";
    public static final String ITEM_test = "test";

    Don't schow…How do i do it properly? Thx