Wednesday, April 6, 2016

Android Populate ListView from JSON – Example

Creating Layout:

The Main layout for our project is “activity_main” which has a ListView to display the array.
<RelativeLayout xmlns:android=""
    tools:context=".MainActivity" >
        android:layout_above="@+id/getdata" />
        android:text="Get Data" />
Next step is to create a layout for the list item that is to be displayed in ListView. Create the layout as list_v.xml which has three TextView’s to display the Array in each list item. Here I have created the TextView’s in LinearLayout.

<script async src="//"></script>
<!-- android help -->
<ins class="adsbygoogle"
(adsbygoogle = window.adsbygoogle || []).push({});

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

Creating Activity:

Before creating the MainActivity we need to create a JSON Parser class which gets the JSON data from the URL and returns JSON Object.
In your Project create a new folder library in the src folder such that the package is “learn2crack.listview.library”. Create the in the library folder.
package smr.listview.library;
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;
import android.util.Log;
public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public JSONParser() {
    public JSONObject getJSONFromUrl(String url) {
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        } catch (UnsupportedEncodingException e) {
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        // return JSON String
        return jObj;
Next step is to create MainActivity.The Button “Get Data” is used to trigger the AsyncTask which process the backgroung Data. Here we are defining the array “oslist” which is displayed as text in ListView. The JSONArray is “android” which we got from the URL. It is then stored in a string. We are using ListAdapter is generate ListView. Finally we are using OnItemClickListener to display the OS in Toast when it is clicked.
package learn2crack.listview;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity {
    ListView list;
    TextView ver;
    TextView name;
    TextView api;
    Button Btngetdata;
    ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
    //URL to get JSON Array
    private static String url = "";
    //JSON Node Names
    private static final String TAG_OS = "android";
    private static final String TAG_VER = "ver";
    private static final String TAG_NAME = "name";
    private static final String TAG_API = "api";
    JSONArray android = null;
    protected void onCreate(Bundle savedInstanceState) {
        oslist = new ArrayList<HashMap<String, String>>();
        Btngetdata = (Button)findViewById(;
        Btngetdata.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                 new JSONParse().execute();
    private class JSONParse extends AsyncTask<String, String, JSONObject> {
         private ProgressDialog pDialog;
        protected void onPreExecute() {
             ver = (TextView)findViewById(;
             name = (TextView)findViewById(;
             api = (TextView)findViewById(;
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Getting Data ...");
        protected JSONObject doInBackground(String... args) {
            JSONParser jParser = new JSONParser();
            // Getting JSON from URL
            JSONObject json = jParser.getJSONFromUrl(url);
            return json;
         protected void onPostExecute(JSONObject json) {
             try {
                    // Getting JSON Array from URL
                    android = json.getJSONArray(TAG_OS);
                    for(int i = 0; i < android.length(); i++){
                    JSONObject c = android.getJSONObject(i);
                    // Storing  JSON item in a Variable
                    String ver = c.getString(TAG_VER);
                    String name = c.getString(TAG_NAME);
                    String api = c.getString(TAG_API);
                    // Adding value HashMap key => value
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(TAG_VER, ver);
                    map.put(TAG_NAME, name);
                    map.put(TAG_API, api);
                    ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
                            new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
                    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        public void onItemClick(AdapterView<?> parent, View view,
                                                int position, long id) {
                            Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {

Creating Manifest:

Add the permision “android.permission.INTERNET” to the Manifest file as we need to access external Address.No other special Permissions are required for our project.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    android:versionName="1.0" >
        android:targetSdkVersion="19" />
        android:theme="@style/AppTheme" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
    <uses-permission android:name="android.permission.INTERNET" />
Finally run the project in the Emulator.
listview json parsing
Project Running in Emulator