ListView using Custom CursorAdapter : example

This is an example of using Lists (ListView) in Android and populating the List with the data from your database which comes in a cursor. So this is an example using custom CursorAdapter.

Definitions:

  • ListView: A view that shows items in a vertically scrolling list.
  • Cursor: This interface provides random read-write access to the result set returned by a database query.
  • CursorAdapter: Adapter that exposes data from a Cursor to a ListView widget. The Cursor must include a column named “_id” or this class will not work.
Code in your Activity class
wordsListAdapter wla = new wordsListAdapter(this, cursor);
 ListView lv = (ListView)findViewById(R.id.listView1);
 lv.setAdapter(wla);

Code for defining custom CursorAdapter


public class wordsListAdapter extends CursorAdapter
{
LayoutInflater inflater;
public wordsListAdapter(Context context, Cursor c) {
super(context, c);
inflater = LayoutInflater.from(context);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO Auto-generated method stub
TextView tv1 = (TextView)view.findViewById(R.id.textView1);
TextView tv2 = (TextView)view.findViewById(R.id.textView2);

tv1.setText(cursor.getString(1));
tv2.setText(cursor.getString(2));
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater.inflate(R.layout.word_list_item, parent, false);
}
}
}

External References:
http://developer.android.com