JSON Parsing in Android

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:

You can see a video demo below.

Download Project

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.

Now use the following code in the main activity java file.

Update the layout files as below.
screen1.xml

list_view.xml

Running the app would show you the recent articles from the blog as shown in the following screenshot.

Android JSON Parsing

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.

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:

It requires a manifest permission ACCESS_NETWORK_STATE as shown.
AndroidManifest.xml

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.

android progress dialog

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.

About Hrishikesh Kumar

By Hrishikesh Kumar. An undergrad at IIT Guwahati, India. A programming enthusiast and a learner. He loves his android and builds Android applications in his spare time. Follow me on Google.

, , ,