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

Pre-Requisites 

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

After Inserting Data into MySQL database table myorder ( http://www.tutorialsbuzz.com/2014/12/android-php-insert-mysql-db-volley.html )

PHP Script

1 a. DBConfig

file : db_config.php

<?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

<?php
error_reporting(0);
include(“db_config.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

URL    http://api.tutorialsbuzz.com/Orders/read_allorder.php
Request Type    GET
JSON Output On Success

{“orders”:[
            {“id”:”681″,”item”:”Pizza”},
            {“id”:”690″,”item”:”Pasta”},
            {“id”:”701″,”item”:”Coke”},
            {“id”:”710″,”item”:”Burger”},
            {“id”:”720″,”item”:”Finger-Chips”},
            {“id”:”730″,”item”:”Noodles”}
            ],
 “success”:1} 

 On Failure

 {“success”:0}

Android

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 .

build.gradle

dependencies {
    compile fileTree(dir: ‘libs’, include: [‘*.jar’])
    testCompile ‘junit:junit:4.12’
    compile ‘com.android.support:appcompat-v7:23.1.0’
    compile ‘com.android.support:design:23.1.0’
    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″?>
<RelativeLayout
    xmlns:android=“http://schemas.android.com/apk/res/android”
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”
    android:padding=”10dp” >

    <TextView
        android:id=”@+id/item_name”
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:layout_alignParentLeft=”true”
        android:layout_alignParentTop=”true”
        android:layout_marginLeft=”10dp”
        android:layout_marginTop=”5dp”
        android:textAppearance=”?android:attr/textAppearanceLarge”
        android:textColor=”#000000″ />

    <TextView
        android:id=”@+id/item_id”
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:layout_alignLeft=”@+id/item_name”
        android:layout_below=”@+id/item_name”
        android:textColor=”#000000″ />

    <ImageView
        android:id=”@+id/imageView1″
        android:layout_width=”wrap_content”
        android:layout_height=”30dp”
        android:layout_alignParentRight=”true”
        android:layout_alignTop=”@+id/item_name”
        android:src=”@drawable/fwd” />

</RelativeLayout> 

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 : MyApplication.java

package com.pavan.androidphp;

import android.app.Application;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class MyApplication extends Application {

    private RequestQueue mRequestQueue;
    private static MyApplication mInstance;

    @Override
    public void onCreate() {
        super.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) {

        getReqQueue().add(req);
    }

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

        getReqQueue().add(req);
    }

    public void cancelPendingReq(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

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 : ReadData.java

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.app.ListActivity;
import android.app.ProgressDialog;
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;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

public class ReadData extends ListActivity {

    String url = “http://api.tutorialsbuzz.com/Orders/read_allorder.php”;
    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”;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

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

        PD = new ProgressDialog(this);
        PD.setMessage(“Loading…..”);
        PD.setCancelable(false);

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

        ReadDataFromDB();
    }

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

                    @Override
                    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));
                                    item.put(ITEM_NAME,
                                            jobj.getString(ITEM_NAME));

                                    Item_List.add(item);

                                } // for loop ends

                                String[] from = { ITEM_ID, ITEM_NAME };
                                int[] to = { R.id.item_id, R.id.item_name };

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

                                setListAdapter(adapter);

                                PD.dismiss();

                            } // if ends

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        PD.dismiss();
                    }
                });

        // Adding request to request queue
        MyApplication.getInstance().addToReqQueue(jreq);

    }

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

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

            Intent modify_intent = new Intent(ReadData.this,
                    UpdateDeleteData.class);

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

            startActivity(modify_intent);

        }

    }
}

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
    ReadData.java:106) <-MyApplication.getInstance().addToReqQueue(jreq);
    ReadData.java:51) <-ReadDataFromDB();

  • when i run the apps, there are 2 error log:Caused by: java.lang.NullPointerException
    ReadData.java:106) <-MyApplication.getInstance().addToReqQueue(jreq);
    ReadData.java:51) <-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