Volley Framework – parsing JSON feed

Today we have got Android’s Volley Framework tutorial for you. It was requested by one of our readers. It is an interesting topic so we decided to write this tutorial for you guys. Enjoy.

Android Volley Framework

Android Volley Framework

In this tutorial we parse and display data from our JSON feed (http://www.itcuties.com/feed/json), almost the same way we did in the RSS Parser tutorial (http://www.itcuties.com/android/how-to-write-android-rss-parser/) and ATOM Parser tutorial (http://www.itcuties.com/android/atom-parser/) posts. The difference is that all the JSON parsing logic is done by the Volley framework.

Volley Framework Android - ITCuties JSON Reader

Volley Framework Android – ITCuties JSON Reader

Volley Framework Installation

Let’s begin with installing the Volley framework in you application. Since there is no JAR distribution (as for now) you will need to clone the GitHub repository. You can do that by calling the following command.

git clone https://android.googlesource.com/platform/frameworks/volley

Other easy way of cloning the repository is by using the TortoiseGit.

Volley Framework Android - TortoiseSVN - Git Clone

Volley Framework Android – TortoiseSVN – Git Clone

When you have your local repository cloned from Github you need to copy the com.android.volley directory from the src directory to your project’s src directory. Now you can use Volley Framework in your application.

Using Volley Framework

Here is our sample application code. At the beginning, to avoid the basic first run problem with the network permission, you need to add it to your AndroidManifest.xml file.

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

Here is our data model class which represents the JSON object that we are reading from the JSON feed.

ItcJSONItem.java

package com.itcuties.android.apps.itcvolleyexampleapp.data;

/**
 * This class represents a post.
 * 
 * @author itcuties
 *
 */
public class ItcJSONItem {
	
	private String title;
	
	private String link;

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getLink() {
		return link;
	}

	public void setLink(String link) {
		this.link = link;
	}

	@Override
	public String toString() {
		return title;
	}

}

We are only interested in reading the title and link data from the feed. The important thing is to implement the toString method here because, this method is called by the ListAdapter mechanism when displaying each of the list’s elements.

ListListener.java

package com.itcuties.android.apps.itcvolleyexampleapp.ui.listeners;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.itcuties.android.apps.itcvolleyexampleapp.data.ItcJSONItem;

/**
 * Class implements a list listener
 * 
 * @author itcuties
 *
 */
public class ListListener implements OnItemClickListener {

	// List item's reference
	List<ItcJSONItem> listItems;
	// Calling activity reference
	Activity activity;
	
	public ListListener(List<ItcJSONItem> aListItems, Activity anActivity) {
		listItems = aListItems;
		activity  = anActivity;
	}
	
	public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
		// We create an Intent which is going to display data
        Intent i = new Intent(Intent.ACTION_VIEW);
        // We have to set data for our new Intent
        i.setData(Uri.parse(listItems.get(pos).getLink()));
        // And start activity with our Intent
        activity.startActivity(i);
	}
	
}

This class implements the OnItemClickListener interface. We need the calling activity’s reference to start the browser activity. We need the list containing the json items to get the clicked item URL value from it.

MainActivity.java

package com.itcuties.android.apps.itcvolleyexampleapp;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.itcuties.android.apps.itcvolleyexampleapp.data.ItcJSONItem;
import com.itcuties.android.apps.itcvolleyexampleapp.ui.listeners.ListListener;
import com.itcuties.android.apps.itcvolleyexampleapp.util.listeners.ItcJSONResponseErrorListener;
import com.itcuties.android.apps.itcvolleyexampleapp.util.listeners.ItcJSONResponseListener;
import com.itcuties.apps.R;

/**
 * Main activity displaying a list of ATOM items
 * 
 * @author itcuties
 *
 */
public class MainActivity extends Activity {
 
    // Volley's request queue
    private RequestQueue requestQueue;
    
    // JSON feed items
    List<ItcJSONItem> jsonItems;
    
    /**
     * This method creates main application view
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Set view
        setContentView(R.layout.activity_main);

        // Initialize the items list
        jsonItems = new ArrayList<ItcJSONItem>();
        
        // Get the reference to the ListView
        ListView itcItems = (ListView) findViewById(R.id.listMainView);
        
     	// Create a list adapter
        ArrayAdapter<ItcJSONItem> adapter = new ArrayAdapter<ItcJSONItem>(this,android.R.layout.simple_list_item_1, jsonItems);
        // Set list adapter for the ListView
        itcItems.setAdapter(adapter);
                     
        // Set list view item click listener
        itcItems.setOnItemClickListener(new ListListener(jsonItems, this));
        
        // Create the request queue
        requestQueue = Volley.newRequestQueue(this);

        // Read JSON data
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
        							Request.Method.GET,
        							"http://www.itcuties.com/feed/json",
        							null,
        							new ItcJSONResponseListener(this, adapter, jsonItems),
        							new ItcJSONResponseErrorListener(this));
        
        // Add the request to the queue
        requestQueue.add(jsonObjectRequest);
        
    }
}

This is our activity class where we create the ListView using the ArrayAdapter and ListListener we have shown above. Next we create a RequestQueue using Volley’s newRequestQueue method. At the end the JsonObjectRequest is created and added to the queue.

ItcJSONResponseListener.java

package com.itcuties.android.apps.itcvolleyexampleapp.util.listeners;

import java.util.List;

import org.json.JSONObject;

import android.content.Context;
import android.widget.BaseAdapter;
import android.widget.Toast;

import com.android.volley.Response.Listener;
import com.itcuties.android.apps.itcvolleyexampleapp.data.ItcJSONItem;
import com.itcuties.android.apps.itcvolleyexampleapp.util.ItcJSONUtils;

/**
 * JSON Response listener
 * 
 * @author itcuties
 *
 */
public class ItcJSONResponseListener implements Listener<JSONObject> {
	// Main activity context reference
	private Context context;
	
	// JSON feed items
    List<ItcJSONItem> items;
    
    // List adapter reference
    private BaseAdapter adapter;
	
    // Initialize all the attributes
	public ItcJSONResponseListener(Context context, BaseAdapter adapter, List<ItcJSONItem> items) {
		this.context = context;
		this.items = items;
		this.adapter = adapter;
	}
	
	// Called when JSON data is ready to be parsed 
	public void onResponse(JSONObject response) {
		// Parse JSON results
		ItcJSONUtils.fillList(response, items);
		// Notify the list adapter that the item list is ready
		adapter.notifyDataSetChanged();
		// Display quick info to the user about the success
		Toast.makeText(context, "Loading done !", Toast.LENGTH_LONG).show();
	}
}

This class implements the functionality called when a proper JSON object is returned which is parsing it and filling out the list located under the passed reference. Adapter reference is used to notify the list displayed on the screen that there is new data available – BaseAdapter’s notifyDataSetChanged method is used for that. The context reference is used to display the Toast message.

ItcJSONResponseErrorListener.java

package com.itcuties.android.apps.itcvolleyexampleapp.util.listeners;

import android.content.Context;
import android.widget.Toast;

import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;

/**
 * JSON Error Response listener.
 * 
 * @author itcuties
 *
 */
public class ItcJSONResponseErrorListener implements ErrorListener {
	// Main activity context reference
	private Context context;
	
	// Create the listener object
	public ItcJSONResponseErrorListener(Context context) {
		this.context = context;
	}
	
	@Override
	public void onErrorResponse(VolleyError error) {
		// Notify user about problems with loading JSON data.
		Toast.makeText(context, "Loading failed!", Toast.LENGTH_LONG).show();
	}
}

This class implements the functionality called when an error occurs. The context reference is used to display the Toast message.

ItcJSONUtils.java

package com.itcuties.android.apps.itcvolleyexampleapp.util;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.itcuties.android.apps.itcvolleyexampleapp.data.ItcJSONItem;
/**
 * JSON utility class
 * 
 * @author itcuties
 *
 */
public class ItcJSONUtils {

	/**
	 * Method fills list with data from the JSON response.
	 */
	public static void fillList(JSONObject response, List<ItcJSONItem> items) {
		try{
			// Get the data array containing posts
            JSONArray jsonArray = response.getJSONArray("posts");
            
            // Get each post data
            for(int i=0; i < jsonArray.length(); i++){
            		// Get an object which represents post
                    JSONObject jsonPostObject = jsonArray.getJSONObject(i);
                    
                    // Create a data object and fill it with data 
                    ItcJSONItem item = new ItcJSONItem();
                    item.setTitle(jsonPostObject.optString("title"));
                    item.setLink(jsonPostObject.optString("permalink"));
                  
                    // Add new object to the list
                    items.add(item);
            }
        }
        catch(Exception e) {
        	// Report problems
            Log.e("ITCVolleyExample::ItcJSONParser", "JSON parsing error!");
        }
	}	
}

This class is the Util class. It has the fillList static method which is used to parse out data from a JSON object and store it in the list.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.itcuties.apps"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />
    
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.itcuties.android.apps.itcvolleyexampleapp.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>

For the record, this is our AndroidManifest.xml file.

activity_main.xml

<RelativeLayout 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"
    tools:context=".MainActivity" >

   	<ListView
        android:id="@+id/listMainView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </ListView>

</RelativeLayout>

This is our layout file which only contains the ListView component.

Download this sample code here.

This code is available on our GitHub repository as well.

2 Responses to "Volley Framework – parsing JSON feed"

  1. Gurupriyan says:

    Thank you very much for this tutorial ..

    Reply
  2. Daniel says:

    Hey, great tutorial. Works perfectly when parsing data from your feed. However, I’m having trouble when trying to parse data from MySQL database. I’m using xampp and I have the necessary php scripts for connecting to the database but it just displays a blank screen after “Loading done!”. Could you please help me with the modifications I need to make so that I can successfully connect my app with the database.

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>