Thursday, July 11, 2013

How to populate Android list view from json

In this post I'm going to illustrate how to add items to Android list view from data in json format.
I will use following json format to populate the list view

{"employee":[{"emp_name":"employee1","emp_no":"101700"}]}

First create an Android project, go to res>>layout directory and open activity_main.xml in Graphical  Layout view and delete the default TextView



Next from the Palette open "Composite" and drag a ListView to the layout file.




Here is the code of activity_main.xml file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" >
    </ListView>

</RelativeLayout>

Following is the sample code for MainActivity which  populates Android list view from a json array.
package com.axel.jsonlistview;
package com.axel.jsonlistview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
 //json string
 private String jsonString = "{\"employee\":[{\"emp_name\":\"employee1\",\"emp_no\":\"101700\"},{\"emp_name\":\"employee2\",\"emp_no\":\"101701\"},{\"emp_name\":\"employee3\",\"emp_no\":\"101702\"},"+
        "{\"emp_name\":\"employee4\",\"emp_no\":\"101703\"},{\"emp_name\":\"employee5\",\"emp_no\":\"101704\"},{\"emp_name\":\"employee6\",\"emp_no\":\"101705\"},"+
        "{\"emp_name\":\"employee7\",\"emp_no\":\"101706\"},{\"emp_name\":\"employee8\",\"emp_no\":\"101707\"},{\"emp_name\":\"employee9\",\"emp_no\":\"101708\"},"+
        "{\"emp_name\":\"employee10\",\"emp_no\":\"101709\"},{\"emp_name\":\"employee11\",\"emp_no\":\"101710\"},{\"emp_name\":\"employee12\",\"emp_no\":\"101711\"},"+
        "{\"emp_name\":\"employee13\",\"emp_no\":\"101712\"},{\"emp_name\":\"employee14\",\"emp_no\":\"101713\"},{\"emp_name\":\"employee15\",\"emp_no\":\"101712\"}]}";
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  initList();
  ListView listView = (ListView) findViewById(R.id.listView1);
  SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList, android.R.layout.simple_list_item_1, new String[] {"employees"}, new int[] {android.R.id.text1});
  listView.setAdapter(simpleAdapter);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }
 
 List<Map<String,String>> employeeList = new ArrayList<Map<String,String>>();
 private void initList(){
  
  try{
   JSONObject jsonResponse = new JSONObject(jsonString);
   JSONArray jsonMainNode = jsonResponse.optJSONArray("employee");
  
  for(int i = 0; i<jsonMainNode.length();i++){
   JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
   String name = jsonChildNode.optString("emp_name");
   String number = jsonChildNode.optString("emp_no");
   String outPut = name + "-" +number;
   employeeList.add(createEmployee("employees", outPut));
  }
 }
  catch(JSONException e){
   Toast.makeText(getApplicationContext(), "Error"+e.toString(), Toast.LENGTH_SHORT).show();
  }
 }
 
 private HashMap<String, String>createEmployee(String name,String number){
  HashMap<String, String> employeeNameNo = new HashMap<String, String>();
  employeeNameNo.put(name, number);
  return employeeNameNo;
 }

}

Demo of the application:

Was above information helpful?
Your comments always encourage me to write more...

9 comments:

  1. How to populate Android expandable list view from json

    ReplyDelete
  2. Thanks dear...You save my day!!!!

    ReplyDelete
  3. Hey I am also having the same doubt.. if u get the answer please notify me also

    ReplyDelete
  4. Hey I am also having the same doubt.. if u get the answer please notify me

    ReplyDelete
  5. thanks man it was really helpful.I need one more help i m getting an image in the response can help me how to print an image in list view .

    ReplyDelete
  6. can you help to print an image in the list. In json response i m getting an path of image of live server. It would be great if anyone can help me

    ReplyDelete
  7. hello, there was a error like "java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference" plz help me

    ReplyDelete