Daily Archives: November 16, 2009

Creating a custom CursorAdapter for Android

I’ve been writing a bit more Android code, and came upon the need to write a custom CursorAdapter for a ListView, as the way I wanted to display data from a Cursor was dependent on relationships between different fields of the database.

Of the problems I encountered, the most obvious was when I tried to inflate views using View.inflate(), and found I would get the following error:

UnsupportedOperationException: addView(View, LayoutParams)
is not supported in AdapterView at android.widget.AdapterView

After a bit of rummaging around, I found that the following bit of code would work when attached to a ListView using setAdapter().

public class ExampleCursorAdapter extends CursorAdapter {
	public ExampleCursorAdapter(Context context, Cursor c) {
		super(context, c);
	public void bindView(View view, Context context, Cursor cursor) {
		TextView summary = (TextView)view.findViewById(R.id.summary);
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		LayoutInflater inflater = LayoutInflater.from(context);
		View v = inflater.inflate(R.layout.item, parent, false);
		bindView(v, context, cursor);
		return v;

The above example code doesn’t actually require a CursorAdapter, it would easily be implemented using a SimpleCursorAdapter, but it serves to show the idea. Basicly, get a LayoutInflater from the context, and use the version of inflate() that does not attach to the root view.