Welcome to Connect Android with PHP & MySQL Series Part 2

Summary

In this tutorial i will show you how to access the fetched data from PHP Script using Volley Library,Parse the fetched JSON and show it in ListView

0.) Requirement

To test the communication between WAMP and your android app you must be on same network.For eg. you are connected to same Wireless router on your device and with your computer on which WAMP is running.

1.) Setting up Required Libraries (Volley Library)

Download volley library from here

Add the downloaded jar file to project
Create a new Project in Eclipse File -> New -> Android Application Project -> Fill the required fields.
once the project is succesfully created paste the volley.jar in libs folder (if there is no libs folder then you can make one)

2.) Starting Project

Creating Volley Applicatio class this class will maintain volley objects & request queue.
In your project create a new class named VolleyController.java & extend the class from Application & add following code
VolleyController.java

package com.developerhouse.android.connect;
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
public class VolleyController extends Application {
public static final String TAG_APP = VolleyController.class
.getSimpleName();
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private static VolleyController instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static synchronized VolleyController getInstance() {
return instance;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(getApplicationContext());
}
return requestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (imageLoader == null) {
imageLoader = new ImageLoader(this.requestQueue,
new LruBitmapCache());
}
return this.imageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG_APP : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG_APP);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (requestQueue != null) {
requestQueue.cancelAll(tag);
}
}
}

LruBitmapCache.java

package com.developerhouse.android.connect;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
public class LruBitmapCache extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
@Override
public Bitmap getBitmap(String url) {
return get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}
&nbsp;

Edit AndroidManifest.xml file and add the VolleyController class in <application> tag using android:name
this will execute the class automatically when the app launch & add INTERNET permission because we need to call web services.
AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.developerhouse.android.connect"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:name="com.developerhouse.android.connect.VolleyController"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

We are outputting JSON array from php Script in JSON if the starting tag is [ then it’s a Array else if it is { then it’s a Object

Json Array (Current output)

[{"id":"1","title":"Rickshaw Racer","description":"Get Rickshaw Racer on Google Play","img_url":"http:\/\/s22.postimg.org\/kg4dj2usx\/Icon_Rickshaw_512.png"}]

Json Object

{"id":"1","title":"Rickshaw Racer","description":"Get Rickshaw Racer on Google Play","img_url":"http:\/\/s22.postimg.org\/kg4dj2usx\/Icon_Rickshaw_512.png"}

MainActivity.java

package com.developerhouse.android.connect;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
public class MainActivity extends Activity { 
private ProgressDialog dialog=null ;
private String TAG="Tutorial Connect";
private String tag_json_arry = "json_array_req";
private String url = "http://192.168.1.5";
private String url_file="/fetch.php";
private CustomAdapter adapter;
private ListView list;ArrayList<RowData> rowdata;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=(ListView) findViewById(R.id.listView1);
rowdata=new ArrayList<RowData>();
dialog= new ProgressDialog(this);
dialog.setMessage("Loading...");
dialog.show();
JsonArrayRequest request = new JsonArrayRequest(url+url_file,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString()); try {
for(int i=0;i<response.length();i++){
String title=response.getJSONObject(i).getString("title");
String description=response.getJSONObject(i).getString("description");
String img_url;
img_url = response.getJSONObject(i).getString("img_url");
rowdata.add(new RowData(title, description, img_url));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
adapter=new CustomAdapter(MainActivity.this, rowdata);
list.setAdapter(adapter);
dialog.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
dialog.dismiss();
}
});
// Adding request to request queue
VolleyController.getInstance().addToRequestQueue(request, tag_json_arry);
}
}

Line 22

private String url = "http://192.168.1.5";

Change this to the IP of your computer

How to get IP of the computer ?

Open CMD type ipconfig you will see something like this

How to use IPConfig

How to use IPConfig

check your default Network Adapter IP

the above code will Log the response & show fetched data in ListView so fire up WAMP ,check PHP Script it’s fetching result or not & run your android app if it output something in LogCat then you are good to continue else post the Error in Comment section or search it on Google

 

CustomAdapter.java

this class is Custom Adapter which will fill be filled by listview

package com.developerhouse.android.connect;
import java.util.ArrayList;
import com.android.volley.toolbox.NetworkImageView;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter{
private ArrayList<RowData> result;
private Context context;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity, ArrayList<RowData> data) {
// TODO Auto-generated constructor stub
result=data;
context=mainActivity;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return result.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView title;
TextView description;
NetworkImageView img;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.list_item, null);
holder.title=(TextView) rowView.findViewById(R.id.textView1);
holder.description=(TextView) rowView.findViewById(R.id.textView2);
holder.img=(NetworkImageView) rowView.findViewById(R.id.networkImageView);
holder.title.setText(result.get(position).getTitle());
holder.description.setText(result.get(position).getDescription());
// If you are using NetworkImageView
holder.img.setImageUrl(result.get(position).getImageURL(), VolleyController.getInstance().getImageLoader()); 
return rowView;
}
}

RowData.java

this class contains variable to hold list item data which is Title,Description,Image Url

package com.developerhouse.android.connect;
public class RowData {
private String title;
private String description;
private String img_url;
public RowData(String title,String description,String img_url){
this.title=title;
this.description=description;
this.img_url=img_url;
}
public String getTitle(){
return title;
}
public String getDescription(){
return description;
}
public String getImageURL(){
return img_url;
}
}

 

XML Layout

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.developerhouse.android.connect.MainActivity"
android:orientation="vertical">
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>

list_item.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:orientation="vertical" >
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/networkImageView"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerHorizontal="false" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/networkImageView"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/networkImageView"
android:layout_below="@+id/textView1"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>

Fetched data will show like this

Fetched Data by Tutorial Connect

Fetched Data by Tutorial Connect