In this tutorial, I have discussed JSON parsing along with Progress Dialog and Connection Manager. JSON (JavaScript Object Notation) is a lightweight data-interchange format. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. An example of JSON:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
{ "entries": [ // [ denotes a JSON Array { // { Denotes a JSON Object "id": "007", "name": "James Bond", "email": "james@bond.com", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000007", "home": "00 0000007", "office": "00 0000007" } }, { "id": "MI6", "name": "Hrishikesh", "email": "hrskumar92@gmail.com", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000006", "home": "00 000006", "office": "00 000006" } } . . . . ] } |
You can see a video demo below.
Create a new project and create a new class Parser.java in it.
First, we need to retrieve the JSON data from a web server. I have used YQL to get json of my blog’s feed which can be found here. The class used to parse the json into a JSONObject is as below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
package com.cw.json; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; public class Parser { static InputStream is = null; static JSONObject jsonObject = null; static String json = ""; // class constructor public Parser() { } public JSONObject getJSONFromUrl(String url) { // Making HTTP request try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException exception) { exception.printStackTrace(); } catch (ClientProtocolException exception) { exception.printStackTrace(); } catch (IOException exception) { exception.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sBuilder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sBuilder.append(line + "\n"); } is.close(); json = sBuilder.toString(); } catch (Exception exception) { exception.printStackTrace(); } // Parsing the string to a JSON object try { jsonObject = new JSONObject(json); } catch (JSONException exception) { exception.printStackTrace(); } // JSON String return jsonObject; } } |
Now use the following code in the main activity java file.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
package com.cw.json; 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.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.widget.ListAdapter; import android.widget.SimpleAdapter; import android.widget.Toast; public class AndroidJSONActivity extends ListActivity { private ProgressDialog progressDialog; // JSON Node names private static final String TAG_QUERY = "query"; private static final String TAG_RESULT = "results"; private static final String TAG_ITEM = "item"; private static final String TAG_TITLE = "title"; private static final String TAG_DATE = "pubDate"; // Hashmap for ListView ArrayList<HashMap<String, String>> entryList = new ArrayList<HashMap<String, String>>(); Parser jParser = new Parser(); // JSONArray JSONArray item = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.screen1); //url from where the JSON has to be retrieved String url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20feed%20where%20url%3D%22http%3A%2F%2Ffeeds.feedburner.com%2FCollegewiresAndroid%22&format=json&diagnostics=true&callback="; //Checking if the user has an internet connection. If negative, show a toast ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); if (info != null) { if (!info.isConnected()) { Toast.makeText(this, "Please check your wireless connection and try again.", Toast.LENGTH_SHORT).show(); } //if positive, fetch the articles in background else new fetchArticles().execute(url); } else { Toast.makeText(this, "Please check your wireless connection and try again.", Toast.LENGTH_SHORT).show(); } } class fetchArticles extends AsyncTask<String, String, String> { // progress dialog while task is being carried on in background @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = new ProgressDialog( AndroidJSONActivity.this); progressDialog.setMessage("Loading ..."); progressDialog.setIndeterminate(false); progressDialog.setCancelable(false); progressDialog.show(); } //fetching all articles from the json and arrange them in list view @Override protected String doInBackground(String... args) { String url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20feed%20where%20url%3D%22http%3A%2F%2Ffeeds.feedburner.com%2FCollegewiresAndroid%22&format=json&diagnostics=true&callback="; JSONObject json = jParser.getJSONFromUrl(url); try { // Getting Array of Entries JSONObject query = json.getJSONObject(TAG_QUERY); JSONObject results = query.getJSONObject(TAG_RESULT); item = results.getJSONArray(TAG_ITEM); // looping through all items for(int i1 = 0; i1 < item.length(); i1++){ JSONObject c = item.getJSONObject(i1); // Storing each json item in variable String title = c.getString(TAG_TITLE); String date = c.getString(TAG_DATE); // new HashMap HashMap<String, String> hashMap = new HashMap<String, String>(); // adding each child node to HashMap key => value hashMap.put(TAG_TITLE, title); hashMap.put(TAG_DATE, date); // adding HashList to ArrayList entryList.add(hashMap); } } catch (JSONException e) { e.printStackTrace(); } runOnUiThread(new Runnable() { public void run() { //updating listview with the parsed items ListAdapter adapter = new SimpleAdapter(AndroidJSONActivity.this, entryList, R.layout.list_item, new String[] { TAG_TITLE, TAG_DATE }, new int[] {R.id.title, R.id.date }); setListAdapter(adapter); } }); return null; } //on execution of the task, dismiss the progress dialog protected void onPostExecute(String args) { progressDialog.dismiss(); } } } |
Update the layout files as below.
screen1.xml
|
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content"/> </LinearLayout> |
list_view.xml
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:background="#eee"> <!-- Name Label --> <TextView android:id="@+id/title" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#ff0a0a" android:textSize="16sp" android:textStyle="bold" android:paddingTop="6dip" android:paddingBottom="2dip" /> <TextView android:id="@+id/date" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#000" android:textSize="10sp" android:paddingTop="6dip" android:paddingBottom="2dip" /> </LinearLayout> </LinearLayout> |
Running the app would show you the recent articles from the blog as shown in the following screenshot.

Running the app shows the recent articles form this blog in a List View
Clicking on the items doesn’t work here. However, you can launch a new activity on clicking the item and show the article’s description and contents. It can be done as below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// selecting single ListView item ListView lv = getListView(); // Launching new screen on Selecting Single ListItem lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // getting values from selected ListItem String title = ((TextView) view.findViewById(R.id.title)).getText().toString(); String date = ((TextView) view.findViewById(R.id.date)).getText().toString(); // Starting new intent Intent in = new Intent(getApplicationContext(), SDescription.class); in.putExtra(TAG_TITLE, title); in.putExtra(TAG_DATE, date); startActivity(in); } }); |
Learn more about switching between Android activities.
One of the few minor problems I have solved here is that an app force closes if the user has no internet connection. I have used the code from my previous tutorial on Android HTTP Access in my main activity file. The code to check if the user has network connection is:
|
1 2 3 4 5 6 7 8 9 10 11 |
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); if (info != null) { if (!info.isConnected()) { Toast.makeText(this, "Please check your connection and try again.", Toast.LENGTH_SHORT).show(); } else **do something here** } else { Toast.makeText(this, "Please check your connection and try again.", Toast.LENGTH_SHORT).show(); } |
It requires a manifest permission ACCESS_NETWORK_STATE as shown.
AndroidManifest.xml
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.cw.json" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:label="@string/app_name" android:name=".AndroidJSONActivity" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> </manifest> |
Progress Dialog
As stated in the documentation, a ProgressDialog is an extension of the AlertDialog class that can display a progress animation in the form of a spinning wheel, for a task with progress that’s undefined, or a progress bar, for a task that has a defined progression. The dialog can also provide buttons, such as one to cancel a download.
Running the following code snippet would output a spinning wheel as shown.
|
1 2 |
ProgressDialog dialog = ProgressDialog.show(this, "", "Loading. Please wait...", true); |

Android Progress Dialog
Progress bar shows the user that a task is being done in the background. If you don’t use this, the device screen might look like that the app has frozen. Progress bar can be used to show progress while downloading some file from the server. Stay tuned for the next post on Progress Dialog.







