Android – Simple ListView using SimpleAdapter

In Android Applications, ListView helps you to display the contents of an array with flexible size. The following example shows you how to create a simple ListView.

1. First create a new Android project

2. Create the following Java class

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

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class ListViewA extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ListView lv= (ListView)findViewById(R.id.listview);

        // create the grid item mapping
        String[] from = new String[] {"rowid", "col_1", "col_2", "col_3"};
        int[] to = new int[] { R.id.item1, R.id.item2, R.id.item3, R.id.item4 };

        // prepare the list of all records
        List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
        for(int i = 0; i < 10; i++){
        	HashMap<String, String> map = new HashMap<String, String>();
        	map.put("rowid", "" + i);
        	map.put("col_1", "col_1_item_" + i);
        	map.put("col_2", "col_2_item_" + i);
        	map.put("col_3", "col_3_item_" + i);
        	fillMaps.add(map);
        }

        // fill in the grid_item layout
        SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.grid_item, from, to);
        lv.setAdapter(adapter);
    }
}

 

 

3. Create the following 2 layouts
main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/main"
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_height="fill_parent"
	android:layout_width="fill_parent">
	<!-- Header -->
	<LinearLayout android:id="@+id/header"
		android:background="#ff347c12"
		android:layout_height="wrap_content"
		android:layout_width="fill_parent"
		>
		<TextView android:id="@+id/item1"
			android:layout_height="fill_parent"
			android:layout_width="wrap_content"
			android:width="20dip"
			android:height="30dip"
		/>
		<TextView android:id="@+id/item2"
			android:layout_height="fill_parent"
			android:layout_width="wrap_content"
			android:text="col_1_h"
			android:width="100dip"
			android:height="30dip"
		/>
		<TextView android:id="@+id/item3"
			android:layout_height="fill_parent"
			android:layout_width="wrap_content"
			android:text="col_2_h"
			android:width="100dip"
			android:height="30dip"
		/>
		<TextView android:id="@+id/item4"
			android:layout_height="fill_parent"
			android:layout_width="wrap_content"
			android:text="col_3_h"
			android:width="100dip"
			android:height="30dip"
		/>
	</LinearLayout>

	<!-- List Divider -->
	<View android:layout_width="fill_parent"
		android:layout_height="1dip"
		android:background="?android:attr/listDivider" />

	<!-- ListView (grid_items) -->
	<LinearLayout android:id="@+id/layout"
		android:layout_width="wrap_content"
		android:layout_height="fill_parent">
		<ListView android:id="@+id/listview"
			android:layout_height="fill_parent"
			android:layout_width="fill_parent">
		</ListView>
	</LinearLayout>
</LinearLayout>

 

 

grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
        <TextView android:id="@+id/item1"
        	android:text="row_id"
        	android:layout_height="fill_parent"
        	android:layout_width="wrap_content"
        	android:width="20dip"
        />
        <TextView android:id="@+id/item2"
	        android:text="col_1"
	        android:layout_height="fill_parent"
	        android:layout_width="wrap_content"
	        android:width="100dip"
	    />
	    <TextView android:id="@+id/item3"
	        android:text="col_2"
	        android:layout_height="fill_parent"
	        android:layout_width="wrap_content"
	        android:width="100dip"
	    />
	    <TextView android:id="@+id/item4"
	        android:text="col_3"
	        android:layout_height="fill_parent"
	        android:layout_width="wrap_content"
	        android:width="100dip"
	    />
</LinearLayout>

 

 

4. Try it!

Done =)

Update 2010-03-15 (Suggested by Mike)
If you want change the background color of the rows in the ListView. Take a look at Android – Applying Alternate Row Color in ListView with SimpleAdapter.

98 thoughts on “Android – Simple ListView using SimpleAdapter

  1. Hi,

    This works beautifully! Thanks!
    However, I haven’t been able to make these list items clickable. I want to be able to launch a new activity with some params when a user clicks on one of the items.

    The code that I’ve added is as below:

    lv.setOnItemClickListener(new OnItemClickListener() {
    
      public void onItemClick(AdapterView adapterView, View view, int position, long id) {
        SimpleAdapter adapter = (SimpleAdapter) adapterView.getAdapter();
        ListView currentLv = (ListView) view;
    				
        Object item = adapter.getItem(position);
        //Do some more stuff here and launch new activity
    				
    				
      }
    });
    

    However, the items remain unclickable – I can select them using my the navigation keys but again there is no action that leads it to go to this piece of code.

    Please help me here! I need to get this Click Event working…

    Thanks,

    Varun

  2. Hi can you help me out with this?
    This is the example from the android developer website, HelloListView.

    I’m having some problems over here ->

    lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView parent, View view, int position, long id) 
      {
        // When clicked, show a toast with the TextView text
        Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
        Toast.LENGTH_SHORT).show();
      }
    });
    

    The onItemClickListener and View view having problems. Can you help me out? Thanks!

  3. Hi there, I have stored data in my sqldatabase and i want to show it out in listview, but i’m not able to.

    Do you have a sample of that? Both are textviews.

  4. Hello there,

    I would like to use this example code, but the items of the list to be a list after an XML Parsing..

    In otherwords, i want to parse an XML and after that to make a list like this one you’ve already made.. :S

    • (Forgot to mention: Thanks a lot for a good example!)

      Seems that the comment system ate my XML… Basically I replaced the LinearLayout in main.xml line 48 with a ScrollView. Also tried to add the ScrollView above the LinearLayout so that the SV contains the LL — same output.

  5. My bad, rookie-mistake: I didn’t have the android:fillViewport=”true” -tag on the scroll view… That took care of it and now it works nicely, scrolling the dynamic list.

    Sorry to spam your comments too soon before studying the problem enough. :)

  6. HI,
    nice tutorial! it helped me a lot, thanks!
    i have just 1 question … how can i change settings of textviews in grid_item.xml programmatically? like

    TextView item1 = (TextView)findViewById(R.id.item1);
    .....
    item1.setTextColor(Color.YELLOW);
    

    it throws me NullPointerException if i do that =/

    • Did u forget to import the android.graphics.Color

      try

      ...
      item1.setTextColor(android.graphics.Color.YELLOW);
      ...
      

       

      or you can define your own color in the resource file. Create the res/values/color.xml

      <?xml version="1.0" encoding="utf-8"?>
      <resources>
        <color name="orange">#ff5500</color>
        <color name="white">#ffffff</color>
      </resources>
      

       

      Then you should be able to set the color by

      ...
      item1.setTextColor(R.color.orange);
      ...
      

       

      Reference: Stack Overflow – Android color xml resource file

      • i solved problem by makeing my own adapter like you did in one other tutorial. problem is, that anything i want to do with TextViews in grid_item.xml, it throws me an NullPointerException,

      • I didn’t meet your problem. i added the setTextColor() function in the in OnItemClickListener as follow.

        OnItemClickListener itemClickedListener = new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub    
            TextView item2 = (TextView)view.findViewById(R.id.item2);
            item2.setTextColor(android.graphics.Color.YELLOW);
        	}
        };
        

        I guess you have missed sth, are u sure u have imported all the required class?

  7. Hi there,
    I’ve created one calendar, on clicking any day of the calendar it will show the list of audio recordings for the day, but now on clicking any one of these recordings it must play it, i’m unable to implement this part. please help me out..

    Thanx..

  8. Hi,

    thanks for your code and the explantions. However, I cannot get it to work: it always throws a null-pointer exception in line 35: lv.setAdapter(adapter);

    I have copied your code 1:1, and I am not able to find the error… Do I miss something obvious perhaps?

    BTW, I am developing on Android 2.2…

  9. Hey, thank you for making this blog entry. I always need to come back an copy your example whenever I need to build a list. This is truly helpful! Thank you!

    • Hi Juhani,

      Good to know that it could help u. As Douglas Merrill said…
      Knowledge is not power. The SHARING of knowledge is power..

      By the way, ur blog looks great!

      Regards,
      Kit

  10. great example.. one thing I wuld like to add, say to the last column is a url link. so when I user clicks it it opens the browser…now I’m able to create the link OK with linkify but when I try to apply to the listview it only shows the text of the link but is not an actual link.

    Any idea how to apply the link to the 3rd column.

  11. i used hashmap for customized listview but only 5 random items are displaying what is the problem?

    public class MyCustomListView extends ListActivity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.custom_list_view);
            
            SimpleAdapter adapter = new SimpleAdapter(this,list,R.layout.custom_row_view,
            		new String[] {"name","height"},
            		new int[] {R.id.text1,R.id.text2}
            		);
            populateList();
            setListAdapter(adapter);
        }
        
        static final ArrayList&lt;HashMap&gt; list = 
        	new ArrayList&lt;HashMap&gt;(); 
    
        private void populateList() {
        	HashMap temp = new HashMap();
        	temp.put("name","Chavand");
        	temp.put("height", "3400ft");
        	list.add(temp);
        	HashMap temp1 = new HashMap();
        	temp1.put("name","Durg-Dhakoba");
        	temp1.put("height", "3900ft &amp; 4100ft");
        	list.add(temp1);
        	HashMap temp2 = new HashMap();
        	temp2.put("name","Hadsar");
        	temp2.put("height", "3200ft");
        	list.add(temp2);
        	HashMap temp3 = new HashMap();
        	temp3.put("name","Jivdhan");
        	temp3.put("height", "3754ft");
        	list.add(temp3);
        	HashMap temp4 = new HashMap();
        	temp4.put("name","Korigad");
        	temp4.put("height", "3000ft");
        	list.add(temp4);
        	HashMap temp5 = new HashMap();
        	temp.put("name","Lohgad");
        	temp.put("height", "3400ft");
        	list.add(temp5);
        	HashMap temp6 = new HashMap();
        	temp.put("name","Malhargad");
        	temp.put("height", "3100ft");
        	list.add(temp6);
        	HashMap temp7 = new HashMap();
        	temp.put("name","Shivneri");
        	temp.put("height", "3500ft");
        	list.add(temp7);
        	HashMap temp8 = new HashMap();
        	temp.put("name","Visapur");
        	temp.put("height", "3038ft");
        	list.add(temp8);
    
        }
    
  12. Hi, I have a question regarding the handling of the listview, I have a project where I show a set of objects (images, text, buttons) but from what I suppose I have a set of 3 buttons in the listview and I want to click on any buttons and these give me back an event, but I see the contents of the listview methods do not work, when clicking on them fails. I used simpleadapter and I tried to take the focus listview below shows the code.

    public class Framemain extends ListActivity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        
            int n=6;
            String []titulo = new String[n];
            String []genero = new String[n];
            String []descripcion = new String[n];
            String []paisorigen = new String[n];
            String []lenguaje = new String[n];
            String []director = new String[n];
            String []actores = new String[n];
            String []clasificacion = new String[n];
            String []duracion = new String[n];
            String []paginaweb = new String[n];
            String []cine = new String[n];
           int[]imagenes= new int[n];
            String[]valoraciones= new String [n];
            
        imagenes[0]=R.drawable.p1;
        imagenes[1]=R.drawable.p2;
        imagenes[2]=R.drawable.p3;
        imagenes[3]=R.drawable.p4;
        imagenes[4]=R.drawable.p5;
        imagenes[5]=R.drawable.p6;
        try {
    InputStream is = getResources().openRawResource(R.raw.peliculas);
    BufferedReader bf= new BufferedReader(new InputStreamReader(is));
        while(bf.ready()){
        	for(int i=0;i<n;i++){
        		titulo[i]=bf.readLine();
        		genero[i]=bf.readLine();
        		descripcion[i]=bf.readLine();
        		paisorigen[i]=bf.readLine();
        		lenguaje[i]=bf.readLine();
        		director[i]=bf.readLine();
        		actores[i]=bf.readLine();
        		clasificacion[i]=bf.readLine();
        		duracion[i]=bf.readLine();
        		paginaweb[i]=bf.readLine();
        		cine[i]=bf.readLine();
        		valoraciones[i]=bf.readLine();
        	}//fin del for
        	}//fin del while
        }//fin del try
    
        catch (Exception e) {
           Log.v("Error de Exception", "no funco");
          }  
        ArrayList<HashMap> arreglo=new ArrayList<HashMap>();
    
        for(int i=0;i<n;i++){
        HashMap map=new HashMap();
        map.put("titulo", titulo[i]); 
        map.put("imagen", imagenes[i]); 
        map.put("descripcion", descripcion[i]);
        arreglo.add(map); 
    }//map
        
        String[] from={"titulo","imagen","descripcion"}; 
        int[] to={R.id.titulo,R.id.imagenpelicula,R.id.descripcion};
       
        SimpleAdapter adapter=new SimpleAdapter(
                        this.getApplicationContext(),
                        arreglo,
                        R.layout.content,
                        from,
                        to);
        //cambiarimagen();
        
        final ListView l = (ListView)findViewById(R.id.ListView);
        l.setAdapter(adapter);
        
        } 
    

    and this is the main.xml

    and there is the content.xml:

    can you help me ?

  13. Pingback: androidtutorialbyal.com » Blog Archive » List View Tutorial For Android

  14. Hi.
    I am geting a erroer ” Cannot cast from View to ListView” for this line of code

    ListView lv= (ListView)findViewById(R.id.listview);

    Plz….can u help me

  15. Hello! I hope you can help me.
    I have two activities, first is main (with ListView and HashMap) and second is an activity with EditText in it.
    My task is to get string from EditText in second activity and put it on ListView in the first one.
    I know how to use Intents and all that stuff, but I have a little problem. It’s only possible to add one unique item into ListView. For example, when I’m adding second item, I get two identical items. When I’m adding third item, ListView has three same items. All items contain the data of last added item. Here’s some code:

    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) {     
      super.onActivityResult(requestCode, resultCode, data); 
      switch(requestCode) { 
        case (STATIC_INTEGER_VALUE) : { 
          if (resultCode == Activity.RESULT_OK) { 
            String Route = data.getStringExtra("route");
            String Destination = data.getStringExtra("destination");
            String Time = data.getStringExtra("time");
            map.put("time", Time);
            map.put("route", Route);
            map.put("destination", Destination);
            fillMaps.add(map);
            SpecialAdapter adapter = new SpecialAdapter(this, fillMaps, R.layout.grid_item, from, to);
            list.setAdapter(adapter);
          } else if (resultCode == Activity.RESULT_CANCELED){
              //Do nothing  
          }
          break;
        } 
      } 
    }
    
    • how about this

      @Override
      public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode) {
          case (STATIC_INTEGER_VALUE) : {
            if (resultCode == Activity.RESULT_OK) {
              String Route = data.getStringExtra("route");
              String Destination = data.getStringExtra("destination");
              String Time = data.getStringExtra("time");
              // create a new map object for every new record
              HashMap<String, String> map = new HashMap<String, String>();
              map.put("time", Time);
              map.put("route", Route);
              map.put("destination", Destination);
              fillMaps.add(map);
              SpecialAdapter adapter = new SpecialAdapter(this, fillMaps, R.layout.grid_item, from, to);
              list.setAdapter(adapter);
            } else if (resultCode == Activity.RESULT_CANCELED){
                //Do nothing
            }
            break;
          }
        }
      }
      
  16. Pingback: Burak ÖZKAN » Blog Arşivi » Android – Custom Listview Ayraç Ekleme

    • In my example, i used a for loop to fill in the listview

      ...
      for(int i = 0; i < 10; i++){
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("rowid", "" + i);
        map.put("col_1", "col_1_item_" + i);
        map.put("col_2", "col_2_item_" + i);
        map.put("col_3", "col_3_item_" + i);
        fillMaps.add(map);
      }
      ...
      

       

      if you want to fill in the remaining space of the parent layout, you could add more items in the fillMaps object. but it is difficult to get the exact number of rows to fill in the remaining space becoz android phones has varied screen size.

      • Yep its really difficult as we have to calculate the height of the listview and list_element height, then we should try filling the list i guess.
        Will post soon if i got solution. Thanks for ur good blog!!!!.

      • Hi,
        As your example how you can fill with data getting from edittexts using add button with increment rows?
        I can show UI like this,
        TextView1 EditText1
        TextView2 EditText2
        Button1
        ListView with two columns

        Please help me…

      • Hi Gaya,

        In my example, i only show some static data in the listview. If you want to allow user to add the listview item, probably you need a sqlite db to store the input data and need a form for getting the user input. The following example should be a nice reference for you.
        Android developers – Notepad Tutorial

        Hope this help.

        Kit

  17. Hi ykyuen,
    I am using a special adapter which extends simpleadapter. In my code I am looping through my collection which is in an ArrayList object. I get the desired items and put them into an hashmap object. Finally I add that hashmap into another arraylist and provide it to the specialadapter, similar to what you have done..Now my PROBLEM is I am getting an “ArrayIndexOutOfBound” error when the code reaches the getView() in the simpleadapter, due to which there is a force close. Now I am not able to figure out which array gets out of bounds…Please clear my confusion..

    Thanking you,
    Gautam.

      • public class SpecialAdapter extends SimpleAdapter 
        {  
        
          private int[] colors = new int[] { 0x30F0F8FF, 0x60C6E2FF, 0x80B9D3EE, 0x909FB6CD };
          public SpecialAdapter(Context context, List<HashMap> items, int resource, String[] from, int[] to) 
          {  
            super(context, items, resource, from, to);  
          }
          @Override 
          public View getView(int position, View convertView, ViewGroup parent)
          {  
            HashMap hm=(HashMap) super.getItem(position);
            View view = super.getView(position, convertView, parent);  //<==== This the line where I get Arrayindexoutofbounds......
        		       
        		      
            return view;  
          }
        

        Now I dont understand why it happens…

      • Will it throw the Arrayindexoutofbounds error if you comment the

        //HashMap hm=(HashMap) super.getItem(position);
        
      • Yes it throws the same even on comment…See I am using the CalendarView and on a particular DAY click I fetch corresponding data from DB, loop it, put it in hashmap and populate it in listview… listview.setAdapter(adapter) also works fine..But when it comes to getView() I dont understand what index postion in the listview goes outOfBounds…..

      • I think the problem is now(TYPO: should be NOT) on your SpecialAdapater class.
        does your IDE supports debug perspective which allows you to adding break points and watches on the code and vaiables?

        check the whole error dump, you should be able to find which line of code cause the error.

      • Yes after doing all that Ive came to the conclusion that the line
        ” View view = super.getView(position, convertView, parent); ”
        gives the error… Have you had any hands on using a CalendarView in your app any time…I mean what I am doing might be a very basic thing to do in calendars…Do you have any experience as to how it can be done…???

      • O Sorry, i think i have a typo in my previous comment. i mean the problem is NOT on your SpecialAdapater class.

        And i haven’t worked with CalendarView before. Actually i created this example 2 years ago with SDK 1.6. Sorry that i can’t help much.

  18. Hi Kit
    I have successfully adapted your code for my project, thanks.
    Now I want to programatically change font size of the text views but I am unable to figure out how to reference them.
    Any suggestions?

    • you can set the font size by the setTextSize() function.

      or edit the xml as follow.

      <TextView android:id="@+id/item1"
        android:layout_height="fill_parent"
        android:layout_width="wrap_content"
        android:width="20dip"
        android:height="30dip"
        android:textSize="30sp"
       />
      
      • Thanks Kit, I understand the setTextSize() function call, I just can’t work out how to reference the TextView at run time. Everything I have tried returns a null pointer.

    • Do you mean AutoCompleteTextView?

      I didn’t quite get what you mean, the list view is for displaying a list of items and the AutoCompleteTextView is for user to enter a value.

      Do you mean letting the user enter a value in the AutoCompleteTextView and then save it to the listview?

      • Hi
        Yes I mean to AutoCompleteTextView.
        Now i have a value in the AutoCompleteTextView(ArrayList Type) and then save it to the listview?

        Thanks
        (Sorry my language very weakness)

      • In that case, you need to collect the user input and save this to a sqlite database.
        i think the following tutorial is useful for you
        Android developers – Notepad Tutorial
        and you could use AutoCompleteTextView when collecting user input.

        The listview shown in this blog post only displays static data. after you could save the user input into database. you should be able to retrieve the data from it and show them in listview.

        hope the above info could help. =)

  19. I tried all the suggest method here to capture the click event to get the row content and display them in a toast but still no success :( .

    Please help.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s