Android JSON Parsing Tutorial – Using AQuery

I hope you folks understood how easy it is to develop Android application with AQuery library in handling image loading, making asynchronous call and lot more from my previous posts. If not take a look at the below posts and they are prerequisite to develop the Application which I am going to teach you in this post.

Introduction to AQuery – Android Query
AQuery Button Listener
AQuery AJAX Callback
AQuery Image Loading

It’s time to explore the other most wonderful feature of AQuery and that is ‘Asynchronous Network Calls’ to download JSON from remote server. In this post we will be developing simple application to demonstrate how to download JSON from Internet and render it over UI after parsing it. I already wrote a separate article – Android JSON Web Service Tutorial on how to make Asynchronous call to download JSON from Network using Android Dot Net Webservice combo.

Video Demo

Application overview

I believe from the Demo video you got to know what are we going to develop.

  1. Application gonna have two spinner controls – one for Country and other for City
    aquery_app_overview_3
  2. When an item is selected from Country spinner control, an asynchronous call is made to Network to download respective cities as JSON.
    aquery_app_overview_1
  3. Application going to hit http://apps.programmerguru.com/json/getcity.php?country=India when India is selected from Country spinner control and Indian cities will be returned as JSON response
    {
    Cities=["Chennai","Delhi","Kolkata","Mumbai"]
    }
  4. Parse JSON and render the data over City spinner control
    aquery_app_overview_2

Steps to download JSON from Network using AQuery library

  1. Declare a Java String object for http URL
    String url = "http://apps.programmerguru.com/json/getcity.php";
  2. Invoke progress method to show progress bar
    aq.progress(R.id.progressBar1);

    Note that displaying and dismissing progress bar will be taken by AQuery library.

  3. Perform method chaining with progress( ) method and download JSON from Internet by invoking ajax( ) method
    aq.progress(R.id.progressBar1).ajax(url, JSONObject.class, this,"jsonCallback");
  4. Callback method ‘jsonCallback’ will be called once after JSON is downloaded from Internet:
    	public void jsonCallback(String url, JSONObject json, AjaxStatus status) {
    		if (json != null) {
    			//After parsing the JSON render it over UI 
    		} else {
    			//Handle error
    		}
    	}
  5. Syntax of ajax( ) method:
    ajax(url url, type data type, handler object, callback method);

It would be helpful for you if you take a look at AQuery AJAX Documentation to understand the list of supported methods in AQuery to perform http network calls.

Quick Links

Project Structure

  • Create new android project [File >> New >> Android Application Project] with project name AQueryJSONExample
  • Choose Build SDK and minimum required SDK [I chose version 4.1 and 2.2]
  • Enter package name as ‘com.prgguru.example’
  • Click next and select BlankActivity
  • Click next and provide Activity name and Layout name as ‘AQueryJSONExample’ and ‘main’ respectively.

Code Listings

Open main.xml, now you can view the layout as either XML or in graphical view and just replace the XML with below one:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <Spinner
        android:id="@+id/countrySpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Spinner
        android:id="@+id/citySpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
         />

</LinearLayout>

AQueryJSONExample.java
Open AQueryJSONExample.java and replace it with below code. Each line is added with comment and I hope it is self understandable. If you still have any doubt/question, discuss it right away in the comment section.

package com.prgguru.example;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxStatus;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class AQueryJSONExample extends Activity {
	//AQuery object
	AQuery aq;
	//Country Spinner Ctrl Object
	Spinner countrySpinnerCtrl;
	//City Spinner Ctrl Object
	Spinner citySpinnerCtrl;
	//Country Spinner Array Adapter
	String[] countries = { "China", "India", "UK", "US" };
	//Progress bar Object
	ProgressDialog prgDialog;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		//Instantiate AQuery Object
		aq = new AQuery(this);
		countrySpinnerCtrl = (Spinner) findViewById(R.id.countrySpinner);
		citySpinnerCtrl = (Spinner) findViewById(R.id.citySpinner);
		//Set Array adapter with Countries array
		ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getApplicationContext(),
				android.R.layout.simple_dropdown_item_1line, countries);
		countrySpinnerCtrl.setAdapter(adapter1);
		//Looking for Item selection
		countrySpinnerCtrl.setOnItemSelectedListener(new OnItemSelectedListener() {
					// When an item is selected from Country Spinner Control
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						//Get selected Item text
						String selectedCountry = countrySpinnerCtrl.getSelectedItem().toString();
						//Update City Spinner Control with JSON response
						updateCitySpinnerCtrl(selectedCountry);
					}

					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub
					}
				});
	}

	public void updateCitySpinnerCtrl(String country) {
		//JSON URL
		String url = "http://apps.programmerguru.com/json/getcity.php?country="+ country;
		//Make Asynchronous call using AJAX method
		aq.progress(R.id.progressBar1).ajax(url, JSONObject.class, this,"jsonCallback");
	}

	public void jsonCallback(String url, JSONObject json, AjaxStatus status) {
		//When JSON is not null
		if (json != null) {
			String[] cities = null;
			//Create GSON object
			Gson gson = new GsonBuilder().create();
			try {
				//Get JSON response by converting JSONArray into String
				String jsonResponse = json.getJSONArray("Cities").toString();
				//Using fromJson method deserialize JSON response [Convert JSON array into Java array]
				cities = gson.fromJson(jsonResponse, String[].class);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				Toast.makeText(aq.getContext(), "Error in parsing JSON", Toast.LENGTH_LONG).show();
			} catch (Exception e) {
				Toast.makeText(aq.getContext(), "Something went wrong", Toast.LENGTH_LONG).show();
			}
			//Set City adapter with created Java array 'cities'
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_dropdown_item_1line, cities);
			citySpinnerCtrl.setAdapter(adapter);
		} 
		//When JSON is null
		else {
			//When response code is 500 (Internal Server Error)
			if(status.getCode() == 500){
				Toast.makeText(aq.getContext(),"Server is busy or down. Try again!",Toast.LENGTH_SHORT).show();
			}
			//When response code is 404 (Not found)
			else if(status.getCode() == 404){
				Toast.makeText(aq.getContext(),"Resource not found!",Toast.LENGTH_SHORT).show();
			}
			//When response code is other 500 or 404
			else{
				Toast.makeText(aq.getContext(),"Unexpected Error occured",Toast.LENGTH_SHORT).show();
			}
		}
	}

}

Include AQuery.jar
Download AQuery jar from here and place it under lib folder.

Include GSON.jar
Download GSON jar from here and place it under lib folder.

AndroidManifest.xml permission

Don’t forget to add write and internet permissions in AndroidManifest.xml:

    <!-- Permission: Allow application to connect to Internet -->
    <uses-permission android:name="android.permission.INTERNET" />

    <!-- Permission: Allow application to write to SDCard -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


getCity.php
Here is the code for getCity.php. You can even create it in your local server (localhost) and try to access it from inside Android application but make sure you updated the URL in updateCitySpinnerCtrl() method.

<?php
$China = array("Beijing","Shanghai","Hong Kong","Xichang");
$India = array('Chennai','Delhi','Kolkata','Mumbai');
$UK = array('Cambridge','Derby','Liverpool','Oxford');
$US = array('Los Angeles','New York','Chicago','San Diego');
$country = $_GET["country"];
if($country == "India"){
$cityJSON = json_encode($India);
}else if($country == "China"){
$cityJSON = json_encode($China);
}else if($country == "UK"){
$cityJSON = json_encode($UK);
}else if($country == "US"){
$cityJSON = json_encode($US);
}

echo "{Cities=".$cityJSON."}";
?>

[pglinkadssmall1]

Demo

That’s all. It’s time to test our code.

Run the application using emulator or device by right clicking on the project >> Run as >> Android applicaiton >> Choose emulator or device.



Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android  is the installation file similar to exe in windows.

[pglinkadssmall]

If you feel this article is helpful and interesting please spread a word about it to your friends and colleagues by sharing the article in Facebook or Twitter.

You are always welcome to provide your comments and feedback from comment box.

Reference

AQuery documentation
[pgwriteforus]
[pgfeedback]

Related Articles

Author: Android Guru

Share This Post On
468 ad
  • Sam

    It’s pretty simple to perform Asynchronous calls using AQuery. Thanks for the tutorial Guru. It works!! :)

  • siddhu

    wrong with getcity.jsp file name .. check it man

    • Thanks Siddhu for noticing it . Have updated the post. :)

  • Nikhil

    can you please tell the code of http://apps.programmerguru.com/json/getcity.php?country= file

    • Its already there. Anyway I am posting it here:

  • nature

    i am getting an error as Notice: Undefined index: country in C:xampphtdocsandroid_connectselectcountry.php on line 6
    Notice: Undefined variable: cityJSON in C:xampphtdocsandroid_connectselectcountry.php on line 17
    {Cities=} for php file

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares