Understanding the Adapter in the Android SDK

Now, generally when you ask someone, What is Adapter, How do we use it ? Promptly comes the answer, “Adapters are simple tools in Android. There is a data structure like a Java object storing data on one side. SimpleAdapter handles Java objects that can be meaningfully translated into Strings by invoking the objects’ toString() method …. bla bla bla bla… ”

This is where I like to switch off my reading and move on to some other blog. I mean, make it simple to understand, Dont make it worse.. Right ???

So lets try this.

In Android, Adapter is a design pattern, that aims at binding the view with the data. For example, you have a listview that shows things like a dropdown box, you need a array of strings to support that. If you use a Adapter in your code (instead of taking a view and doing something like view.add(data) one by one), as you change the data, the view is affected automatically. Simple right. It binds your data to your view. So that when your view changes, your data changes as well, if you delete a item from your view the array is updated too :). Cool I would say.

ArrayList<HashMap> myList = new ArrayList<HashMap>();
String[] data = new String[] { "line1","line2" } ;
int[] idList = new int[] { R.id.text1, R.id.text2 } ;
SimpleAdapter dataToView = new SimpleAdapter(this, myList, R.layout.two_lines, data, idList);
setListAdapter( dataToView );

Ok, let me take this blog to a new level. Lets study the Adapter class diagram.
Adapter is a Base class inherited by “ArrayAdapter, BaseAdapter, CursorAdapter, HeaderViewListAdapter, ListAdapter, ResourceCursorAdapter, SimpleAdapter, SimpleCursorAdapter, SpinnerAdapter, WrapperListAdapter”

Lets start studying the BaseAdapter first.
It inherits from Adapter and implements SpinnerAdapter and ListAdapter. Now what does this mean ? It means that if you use BaseAdaptre your view can either be a ListView or a SpinnerView. So BaseAdapter is a very useful class I would say.

Now lets look at the remaining list of classes that inherit from Adapter. ArrayAdapter, CursorAdapter, HeaderViewList, ResourceCursor, WrapperList.. All self descriptive.

Hope this was helpful.


One thought on “Understanding the Adapter in the Android SDK

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 )

Google+ photo

You are commenting using your Google+ 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