This tutorial will teach you how to add items to your list from a stored JSON string in an activity. The main idea is that the string will be locally stored in the activity in JSON format and we will use predefined JSON library functions to fetch that data and put it in our list.

Below you can find the screen shot of the application.


About JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It’s easy for humans to read and write it. It’s easy for machines to parse and generate. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages. This includes C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties are what make JSON an ideal data-interchange language.

Adding the ListView

In this part we will add a listview to our XML file.

Drag and drop the listview tag in your layout (it can be found under composite list) or add the below code in your XML file. This will create a simple Listview which we will use later for adding our data.

Snippet 1:

Listing 1:

 Create a file activity_main.xml which contains the main layout.

Populating the ListView from JSON

To  implement the JSON to the listview, follow these steps:

  1. Define JSON Data

    Let’s look at the data we will be adding to our list written in JSON format.


    In the above snippet, country is the name of the array which will be holding our JSON objects in square brackets. country_name and capital are variables of the object. To define the value of the variable follow these simple rules :

    A name/value pair consists of a field name in double quotes, followed by a colon, followed by a value in double quotes.

    Each variable and object is separated by a coma. Notice that the basic JavaScript format is followed in JSON.

  2. Putting JSON Data inside a java String

    We will be saving our data locally for our application. So we will save it as a java string. Here, the important thing to keep in mind is using ‘\’ to skip the special character( ” ).

    1. Snippet3:
  3. Working with the listview:

    Now we need to associate our defined listview to the above defined string and for that we will be using a simpleadapter and set it to our list.


    To read more about the simpleadapter click here.

  4. Defining JSON variables

    To retrieve the items from our string, we will need to define JSON variables for objects and arrays which will hold our string and country variables respectivly.


  5. Adding the data to our string

    To add the data from the string to our list, we will have to apply a simple loop and call the variables defined above for JSON and keep adding them to our list.

    Snippet 6:


Listing 2:

Create a new file


This was all about populating a listview in Android with data JSON. If you have any suggestions or have any errors while implementing this procedure, please feel free to comment below.