Following up to my last post, I would like to show you in detail how to get our custom List to be shown in a ListView follow along.

The first thing we need to do is create out layout files, I have for this example created two layout files, one called main and one called listitems the code is below.




Once you’ve done this you need to create an new ArrayAdapter class specific to your object as such


import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AlertsAdapter extends ArrayAdapter {

	int resource;
	String response;
	Context context;
	//Initialize adapter
	public AlertsAdapter(Context context, int resource, List items) {
		super(context, resource, items);

	public View getView(int position, View convertView, ViewGroup parent)
		LinearLayout alertView;
		//Get the current alert object
		alerts al = getItem(position);
		//Inflate the view
			alertView = new LinearLayout(getContext());
			String inflater = Context.LAYOUT_INFLATER_SERVICE;
			LayoutInflater vi;
			vi = (LayoutInflater)getContext().getSystemService(inflater);
			vi.inflate(resource, alertView, true);
			alertView = (LinearLayout) convertView;
		//Get the text boxes from the listitem.xml file
		TextView alertText =(TextView)alertView.findViewById(;
		TextView alertDate =(TextView)alertView.findViewById(;
		//Assign the appropriate data from our alert object above
		return alertView;


Then on your main activity you may add this items to the list as shown below. Please keep in mind that this tutorial assumes you’ve correctly implemented my web service calls in a previous post.


import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;


public class main extends Activity {
    /** Called when the activity is first created. */
	//ListView that will hold our items references back to main.xml
	ListView lstTest;
	//Array Adapter that will hold our ArrayList and display the items on the ListView
	AlertsAdapter arrayAdapter;
	//List that will  host our items and allow us to modify that array adapter
	ArrayList alrts=null;
    public void onCreate(Bundle savedInstanceState) {
        //Initialize ListView
        lstTest= (ListView)findViewById(;
         //Initialize our ArrayList
        alrts = new ArrayList();
        //Initialize our array adapter notice how it references the listitems.xml layout
        arrayAdapter = new AlertsAdapter(main.this, R.layout.listitems,alrts);
        //Set the above adapter as the adapter of choice for our list
        //Instantiate the Web Service Class with he URL of the web service not that you must pass
        WebService webService = new WebService("");
        //Pass the parameters if needed , if not then pass dummy one as follows
		Map params = new HashMap();
		params.put("var", "");
		//Get JSON response from server the "" are where the method name would normally go if needed example
		// webService.webGet("getMoreAllerts", params);
		String response = webService.webGet("", params);

			//Parse Response into our object
			Type collectionType = new TypeToken>(){}.getType();
			//JSON expects an list so can't use our ArrayList from the lstart 
			List lst= new Gson().fromJson(response, collectionType);
			//Now that we have that list lets add it to the ArrayList which will hold our items.
			for(alerts l : lst)
			//Since we've modified the arrayList we now need to notify the adapter that 
			//its data has changed so that it updates the UI
		catch(Exception e)
			Log.d("Error: ", e.getMessage());

I hope this helps

Tags: , , ,

50 Comments on Android Putting Custom Objects in ListView

  1. Rahul says:

    Wow… It worked like a wonder…

    I m really thankful to you for solving my problems with coding. It will be very helpful for developers, especially for amateurs like me…
    Thank u very much once again… KUDOS to Android developers like u… 🙂

  2. Radjiv says:

    Wow this really looks and works great!!
    I’m just a beginner in Java. Could you perhaps explain (by email?) how a JSON source specifically can effect your Class and Adapter?

    Say we had a source like one from twitter:;rpp=3

    I stumbled to some problems when trying to read out my tweets in a testproject. I have no idea what should be adjusted and in what manner.

  3. Iskuhi says:

    Thank u very much.

  4. blake says:

    i’m having a really weird problem with this coding.. i know i’m very new to android programming and all but i literally copy pasted all of your code from this post and the previous (barring the last three of the april 30th post).. yet even without any problems when i run the program i get the “the application (xxxxx) has stopped unexpectedly” error when it launches

    i’ve created other simpler programs but i’d definitely say i’ve caught on pretty quick so im not completely clueless when it comes to troubleshooting.. but i have to say i’m not sure where to start when it comes to fixing this problem.. any help would be greatly appreciated because this program is very similar to what im trying to eventually create

    • Jose C Gomez says:

      Have you tried stepping through the code in debug mode to see where its breaking? Have you given your application the appropriate permissions to connect to the internet? Step through the code in debug mode and find out where it breaks.

  5. HB says:


    Thank you very much for this code, helped me a lot!

    I’m trying to implement an onClickListener for the ListView but it doesnt appear to be working. Any ideas?

  6. HB says:

    Yes I’m using version 1.6 🙁

    I’m trying to set it on the ListView in the alertsAdapter class.
    But I cant initialise the ListView properly.
    I thought it would just be…

    ListView lstText = (ListView)eventView.findViewById( of the listview);

    but this doesnt work.

    From there I assume I use…


    Is this correct?

  7. Kamen says:


    That was The Code I looked for to handle a custom class as adapter object!

  8. linda says:

    I was wondering if you know anyone who would be interested in a job in IT that has Vantange epicor behind them. It is hard to find that part of things


  9. Saiprasad says:

    Was looking for this.

    Thank you.

  10. Sougata Chandra says:


    I must say , this is an exceptionally good tutorials for the beginners to grasp the knitty gritty of Android programming .
    Waiting for some more tutorials as well.

  11. Giri says:

    The above code is very good example .
    Jose C Gomez can you show how to consume WCF web service ?
    I tried with ksoap2,but i could do it.

    so,can you explain how to consume WCF web service with simple example ???please.

  12. Ryan says:

    Thanks for the tutorial. It is fantastic. I do have one problem though. I need to send a variable through the Web Service URL but have had problems. If I try the GET method (for example, it does not send the any of the variables to the page. It only reads up to the question mark in the URL. Any ideas on how to acheive this?

  13. brolly says:


    thanks a lot for the tutorial, but I have a problem.
    Everything seems to work, but my list remains blank.
    In other words, the alerts are not coming through, I think.

    My browser blocks the site because of malware reasons. (anyone else getting this?)
    Is it possible that my android emulator too blocks this and isn’t able to get the alerts?


  14. Jason says:

    Thanks for this. Nice little bit of code. Well done.

  15. Iulia says:

    Hi, following the steps from this page, I get a strange behaviour.
    I’m using my own Object, the only difference is that it also have a field of type Bitmap that represents an image associated with that object. The image also comes from a server through a web service, implemented using SOAP.

    I can see that what comes from the server is ok, the array contains also the expected values( the alrts array in your example), but I cannot see anything on the screen; it’s like this
    line arrayAdapter.notifyDataSetChanged(); doesn’t refresh the UI.

    By any chance do you have an idea?

  16. Iulia says:

    Never mind, it’s working now. Apparently for me the alerts array need to be built before the line arrayAdapter = new AlertsAdapter(main.this, R.layout.listitems,alrts);

    So I called the web service before and it worked.

  17. Mark says:

    If you get the “Force Close” issue (NullPointer exception) try adding

    into the manifest section of you AndroidManifest.xml. Your app doesn’t have access to the internet.

  18. Mark says:

    If you get the “Force Close” issue (NullPointer exception) try adding the uses-permission android:name=”android.permission.INTERNET” tag into the manifest section of you AndroidManifest.xml. Your app doesn’t have access to the internet.

  19. jdrefahl says:

    Thank you so much for this, but I am still having some major issues figuring out how to adapt this to my JSON.

    As you can see, the structure is a bit more complicated then the Alerts JSON used in the example.. and I am absolutely stumped at how to go about this.

    I have tried altering the JSON and turning it into what I think is considered a Java Object and not an Array like the url before.

    and I was able to loop through the object and toast each “Title”, but no idea how to adapt that then to the list view.. I would much rather use the un-altered .json since thats what’s coming out of the CMS.

    Any help here would be greatly appreciated.. I really need someone to just show me how to do this.. or explain it.. once.. then I can figure out extracting the urls for webviews on my own.

    Please help.

    At the moment, when i change the source url to staging.json, it shows 10 line rows.. I figure thats the ten client_media strings. Now only if I could figure out how to get the key pair for the ID field out and into the listView.

    Anyhelp would be greatly appreciated..


    So what am I exactly trying to do.. basically extract out the “title field”..

  20. assem says:


    thanks a lot for the tutorial, I’m new into Android but would like to learn more about it. Can you send me the project plz.

    Thank u very much.

  21. ichaan says:

    How about populating the code to a normal view instead of list view? Can anybody help me to do this?
    Thank you

  22. Elvis says:

    Shouldn’t your ArrayAdapter declaration be the following instead?

    ArrayAdapter alertsAdapter;

    Or is there an AlertsAdapter class that I must be missing…?

  23. Elvis says:

    Sorry, i missed it at the top.

  24. loveAnd says:

    It’s so easy!!

  25. alex says:

    Hey thank you this was very helpful is there a way you could help me doing something similar to this post, only that i would like to populate a spinner instead a listview.

    thank you.

  26. mohit says:

    Hi, would it be possible to get the project file from you please? im a newbie to android programming. and having trouble following your tutorial. if you could please please email it to me, it would save me like a month!

  27. mohit says:

    im getting these errors:

    txtAlertDate cannot be resolved or is not a field

    The public type AlertsAdapter must be defined in its own file /rest_json_tut/src/josecgomez/com/android/dev/webservice line 15 Java Problem

    main cannot be resolved or is not a field /rest_json_tut/src/josecgomez/com/android/dev/webservice line 31 Java Problem

    lstText cannot be resolved or is not a field /rest_json_tut/src/josecgomez/com/android/dev/webservice line 33 Java Problem

    any ideas any one?

  28. mohit says:

    got rid of the errors.. now having the same issue as blake above

    the application (xxxxx) has stopped unexpectedly” error when it launches

  29. Bianco says:

    Thanks a lot, I have a question in my xml file I add a checkbox. The question is. How can I put a listener?

    this is a peace of my code.

    lstTest = (ListView) findViewById(;
    lstTest.setOnItemClickListener(new OnItemClickListener()
    public void onItemClick(AdapterView lstTest, View view,
    int position, long id)
    Intent intent = new Intent();



  30. Sanman says:

    I cannot compile the code above in eclipse.
    Please help me figure this, so I have four classes in my src folder. I do not see any output on my screen on the emulator.

    Thank you,

  31. Chris Keele says:

    Update: I posted in the article preceding this one about issues with nested Json. After further tinkering, I believe my issues would be better addressed here.

    From what I’ve read Gson should be able to handle the nesting. My list view is still showing completely empty. The only way I’ve deviated from the above code is set the json to “” and made a TabActivity as my main Activity, nesting the project above in one of the views (albeit incorrectly–the view appears over the tabs instead of in the tab body. But that’s another issue altogether, I believe.)

    Any thoughts, anyone? Any issues with blank listviews?

  32. […] 1 – getting the json data Part 2 – parsing the objects created to a custom adapter Part 3 – Lazy loading of […]

  33. Maer says:

    Thanks a lot for the tutorial

  34. Muthanna says:


    I am trying hard to detect why this code is not working on my url, i have checked everything and still frustrated ,I would appreciate any help or hint on that.

    Problem: i am getting noting on listview, the debugger shows that when it is trying to add alerts to the list , it will go to exception,Please help me.

    My URL:

  35. SK says:

    Excellent post. Helped me in the right direction.
    Thanks for your time putting this together!

  36. Guru says:

    Really your code helped a lot… but is there any idea to make them in onclickListener… I m new to android… pls help me… Thanks

  37. Divad says:

    thanks for the tutorial and code! I’m trying to get the onitemclicklistener to get values of the item clicked(to be stored and used elsewhere) with little success. Two ways I found are not working.. anyone got any input/ideas?
    String selectedFromList = (String) (lv.getItemAtPosition(position));
    HashMap o = (HashMap) lv.getItemAtPosition(position);

    both give me a E/AndroidRuntime(508): java.lang.ClassCastException: com.itsymbiotics.bgps.boardlist

  38. dannyD says:

    Thanks MAN! nice code


  39. Krishna says:

    Hi, I want to make custom listview to display chat message, chat user name and user photo. I am getting all data (When user send message and when user receives message). But how to add these content in listview. New row should be appended to listview when new message is coming. Can anybody please help me?

  40. 冯中 says:

    I Can’t get the sourceCode. Can be sent to my mailbox. Thank u veryMuch.

    麻了隔壁的twitter 无法访问

  41. Meena Rengarajan says:

    I am very new to this . Firstly what are the basics shoud i learn by using json ? can anyone help me here..

  42. Sebastian Cheung says:

    Will this also work for a XML from Windows Azure Dto:

    as I want to parse in , ,

  43. ktkim says:

    Thank U very much
    Good Luck~♬

  44. Matteo says:

    amazing! thank you for sharing this!

  45. hasthike says:

    is there any way of download this whole project ??

  46. Zuhoor HA says:

    the simplest solution i found, this is great work thanks alot

  47. Raphael Garcia says:

    Thank you man, this helped me a lot.
    Simple and direct.