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.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
<ListView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"  
    android:id="@+id/lstText"
    />
</LinearLayout>

listitems.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent" android:layout_height="fill_parent">
	<LinearLayout 
	android:orientation="vertical"
	android:layout_width="0dip" android:layout_weight="1"
	android:layout_height="fill_parent">
		<TextView 
		android:layout_width="fill_parent"
		android:layout_height="wrap_content" 
		android:id="@+id/txtAlertText" />
		<TextView 
		android:layout_width="fill_parent"
		android:layout_height="wrap_content" 
		android:id="@+id/txtAlertDate" />
	</LinearLayout>
</LinearLayout>

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

package josecgomez.com.android.dev.webservice;

import java.util.List;

import josecgomez.com.android.dev.webservice.objects.alerts;
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<alerts> {

	int resource;
	String response;
	Context context;
	//Initialize adapter
	public AlertsAdapter(Context context, int resource, List<alerts> items) {
		super(context, resource, items);
		this.resource=resource;

	}
	
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		LinearLayout alertView;
		//Get the current alert object
		alerts al = getItem(position);
		
		//Inflate the view
		if(convertView==null)
		{
			alertView = new LinearLayout(getContext());
			String inflater = Context.LAYOUT_INFLATER_SERVICE;
			LayoutInflater vi;
			vi = (LayoutInflater)getContext().getSystemService(inflater);
			vi.inflate(resource, alertView, true);
		}
		else
		{
			alertView = (LinearLayout) convertView;
		}
		//Get the text boxes from the listitem.xml file
		TextView alertText =(TextView)alertView.findViewById(R.id.txtAlertText);
		TextView alertDate =(TextView)alertView.findViewById(R.id.txtAlertDate);
		
		//Assign the appropriate data from our alert object above
		alertText.setText(al.alerttext);
		alertDate.setText(al.alertdate);
		
		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.

package josecgomez.com.android.dev.webservice;

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

import josecgomez.com.android.dev.webservice.objects.alerts;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

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<alerts> alrts=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //Initialize ListView
        lstTest= (ListView)findViewById(R.id.lstText);
        
         //Initialize our ArrayList
        alrts = new ArrayList<alerts>();
        //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
        lstTest.setAdapter(arrayAdapter);
                
        //Instantiate the Web Service Class with he URL of the web service not that you must pass
        WebService webService = new WebService("http://www.sumasoftware.com/alerts/GetAlerts.php");
        
        //Pass the parameters if needed , if not then pass dummy one as follows
		Map<String, String> params = new HashMap<String, String>();
		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);

		try
		{
			//Parse Response into our object
			Type collectionType = new TypeToken<ArrayList<alerts>>(){}.getType();
			
			//JSON expects an list so can't use our ArrayList from the lstart 
			List<alerts> 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)
			{
				alrts.add(l);
			}
			
			//Since we've modified the arrayList we now need to notify the adapter that 
			//its data has changed so that it updates the UI
			arrayAdapter.notifyDataSetChanged();
		}
		catch(Exception e)
		{
			Log.d("Error: ", e.getMessage());
		}
    }
}
 

I hope this helps

Be Sociable, Share!

Tags: , , ,

48 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:
    http://search.twitter.com/sear.....#038;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

  5. 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.

  6. HB says:

    Hello

    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?

  7. Jose C Gomez says:

    What version are you using? It was harder on 1.6 on newer versions you should use onItemClickListener instead of onClickListener, Give that a shot.

  8. 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(R.id.name of the listview);

    but this doesnt work.

    From there I assume I use…

    lstText.onItemClickListener(){….

    Is this correct?

  9. Kamen says:

    THANK YOU!

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

  10. 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

    Linda

  11. Saiprasad says:

    Was looking for this.

    Thank you.

  12. Sougata Chandra says:

    Hi,

    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.

  13. Giri says:

    Hi,
    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.

  14. 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 http://www.website.com/data.php?id=1), 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?

  15. brolly says:

    Hi,

    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 http://www.sumasoftware.com/alerts/GetAlerts.php 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?

    greets
    brolly

  16. Jason says:

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

  17. 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?

  18. 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.

  19. 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.

  20. 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.

  21. 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.

    http://www.neomod.com/chemopro/staging.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.

    http://www.neomod.com/chemopro/stagingObj.json

    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..

    John

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

  22. assem says:

    hi,

    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.

  23. ichaan says:

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

  24. Elvis says:

    Shouldn’t your ArrayAdapter declaration be the following instead?

    ArrayAdapter alertsAdapter;

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

  25. Elvis says:

    Sorry, i missed it at the top.

  26. loveAnd says:

    It’s so easy!!

  27. 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.

  28. 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!

  29. mohit says:

    im getting these errors:

    txtAlertDate cannot be resolved or is not a field ArrayAdapter.java

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

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

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

    any ideas any one?

  30. 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

  31. 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(R.id.lstText);
    lstTest.setOnItemClickListener(new OnItemClickListener()
    {
    public void onItemClick(AdapterView lstTest, View view,
    int position, long id)
    {
    Intent intent = new Intent();
    intent.setClass(ProductosScreen.this,
    PersonScreen.class);
    startActivity(intent);
    finish();

    }
    });

    Thanks

  32. 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,
    Sanman

  33. 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 “http://app.lsureveille.com/articles.json” 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?

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

  35. Maer says:

    Thanks a lot for the tutorial

  36. Muthanna says:

    Hi,

    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: http://130.240.134.17/gravlax/.....ormat/json

  37. SK says:

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

  38. 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

  39. 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));
    and
    HashMap o = (HashMap) lv.getItemAtPosition(position);

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

  40. dannyD says:

    Thanks MAN! nice code

    //BestKoderEverR
    ——————–

  41. 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?

  42. 冯中 says:

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

    麻了隔壁的twitter 无法访问

  43. 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..

  44. Sebastian Cheung says:

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

    94d5d2ca8b8347c19478bfaaf058ac65.cloudapp.net/api/landingpage/00000000-0000-0000-0000-000000000000

    as I want to parse in , ,

  45. ktkim says:

    Thank U very much
    Good Luck~♬

  46. Matteo says:

    amazing! thank you for sharing this!

  47. hasthike says:

    is there any way of download this whole project ??

Leave a Reply