Adapters are bridging classes that bind data to Views (such as List Views) used in the user interface.
Some Native Adapters
ArrayAdapter The Array Adapter uses generics to bind an Adapter View to an array of
objects of the specified class.
SimpleCursorAdapter The Simple Cursor Adapter attaches Views specified within a lay-
out to the columns of Cursors returned from Content Provider queries.
Customizing the Array Adapter
public class MyArrayAdapter extends ArrayAdapter<MyClass> {
int resource;
public MyArrayAdapter(Context context,
int _resource,
List<MyClass> items) {
super(context, _resource, items);
resource = _resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout newView;
MyClass classInstance = getItem(position);
// TODO Retrieve values to display from the
// classInstance variable.
// Inflate a new view if this is not an update.
if (convertView == null) {
newView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resource, newView, true);
} else {
newView = (LinearLayout)convertView;
}
// TODO Retrieve the Views to populate
// TODO Populate the Views with object property values.
return newView;
}
}
Using Adapters for DataBinding
ArrayList<String> myStringArray = new ArrayList<String>();
ArrayAdapter<String> myAdapterInstance;
int layoutID = android.R.layout.simple_list_item_1;
myAdapterInstance = new ArrayAdapter<String>(this, layoutID , myStringArray);
myListView.setAdapter(myAdapterInstance);
myAdapterInstance.notifyDataSetChanged();
Using the Simple Cursor Adapter
The SimpleCursorAdapter lets you bind a Cursor to a List View, using a custom layout definition to
define the layout of each row/item, which is populated by a row’s column values.
String uriString = "content://contacts/people/";
Cursor myCursor = managedQuery(Uri.parse(uriString), null, null, null);
String[] fromColumns = new String[] {People.NUMBER, People.NAME};
int[] toLayoutIDs = new int[] { R.id.nameTextView, R.id.numberTextView};
SimpleCursorAdapter myAdapter;
myAdapter = new SimpleCursorAdapter(this,
R.layout.simplecursorlayout,
myCursor,
fromColumns,
toLayoutIDs);
myListView.setAdapter(myAdapter);