Android Programming

Adapter

The Adapter is actually an interface defined in the android.widget package.

package android.widget;

It's objects do act as a bridge between the AdapterView and the underlying data for that view. The adapter has two responsibilities:

  1. Provide access to data items.
  2. Make View objects for each item in the data set.

Types of Adapters

Here are the main implementors of the this interface:

  1. android.widget.ArrayAdapter.
  2. android.widget.CursorAdapter.
  3. android.widget.SimpleCursorAdapter.

This interface has some method signatures that will typically be implemented by concrete classes implementing this interface.

Commonly used Methods

Some of them include:

  1. int getCount() : This method returns the total number of items in the data set that this adapter represents.

  2. Object getItem(int position): This method will retrieve the data item that's associated with the specified position in the data set. As a parameter it takes the position of the item whose data we want within the adapter's data set. It will return the an Object which is the data at the specified position.

  3. long getItemId(int position: This method will retrieve the row id that's associated with the specified position in the list. It will take as a parameter the position of the item within the adapter's data set whose row id we want. It will return the id of the item at the specified position.

  4. View getView(int position,View convertView,ViewGroup parent): This method as you cans ee returns an android.view.View object. This returned View object will be responsible for displaying data. This is the data whose position is specified by the integer passed as a parameter in this method.There are two ways of creating this View:

    • Manually by instantiating.
    • Inflation from a Layout resource(most common).

      After the inflation, the adapterview like ListView and GridView will apply the default parameters. Now this happens only if did not use the inflate(int,ViewGroup,boolean) method of the android.view.LayoutInflater class to specify the root view and prevent attachment to the root.

      There are three parameters passed. The position represents the position of the item within the adapter's data set. The convertView. This represents the already inflated View object that we want to reuse. You want to check that this View actually exists by checking if it's not null before using. If it is then you inflate it. It's also possible to create new views for example that can be used by heterogeneous lists. The parent is basically a ViewGroup onto which this view will be attached to.