Using ArrayAdapter and ListView in Android Applications

Using ArrayAdapter and ListView in Android Applications

This week’s homework in the android class was to create a simple ListView using ArrayAdapter instead of generic ListAdapter.

ArrayAdapter

ArrayAdapter is a special kind of ListAdapter which supplies data to ListView. You can refer to my notes for last week to know about ListView and ListAdapter. You can also read about ArrayAdapter in android documentation.

Adding views

First create an empty android project. Then edit the main.xml layout file to add a ListView. Then create another layout xml file which will contain the TextView (or any component) that will be displayed within the ListView.

Editing Activity

The next step is to change the generated activity class to extend from ListActivity. This is very important because only a ListActivity will be able to display the ListView.

Binding the adapter

The next step is to bind the ArrayAdapter to the ListActivity. We can do this by calling the setListAdapter() method.

To this method we have to pass an object of type ArrayAdapter. You can pass an object reference to this method or we can even create a new anonymous method like below.

setListAdapter(new ArrayAdapter<string>(this, R.layout.list_item, strings) {
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row;
 
		if (null == convertView) {
			row = mInflater.inflate(R.layout.list_item, null);
		} else {
			row = convertView;
		}
 
		TextView tv = (TextView) row.findViewById(android.R.id.text1);
		tv.setText(getItem(position));
 
		return row;
	}
});

We have to override the getView() method of the ArrayAdapter class to create the TextView (or any other component) which will be created for each list.

Finishing up

So that’s it, you are done. :) All you have to do now is to save the project and run it in the emulator. If everything is done properly, then you can see the list of items displayed in the ListView like below.

android-listview

Source code

I have uploaded the entire project source code into github and you download it from there and verify it with your code.

Try to complete the homework, before the next session and do come back to view the notes and the homework for the next session too. :)

You can also subscribe to my blog’s RSS feed or follow me in Twitter to receive updates about my notes for the next sessions.

Possibly Related posts

Tags: , ,

Share thy love

2 Comments so far

Trackback URI | Follow up comments through RSS Feed | Post a comment

2 Tweetbacks so far

Leave a Comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">