KIO
Kreative Ideen online
Cursor adapter

Cursor adapter

How to use a simple cursor adapter

You initialize te adapter, then attach it to the list view.

SimpleCursorAdapter listAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,cursor,new String[]{"NAME", new int[]{android.R.id.text1},0);

//Use setAdatper() to connect the adatper to the list view.
listDrinks.setAddapater(listAdapter);

cursor: This is the cursor

new String[]{“NAME”, new int[]{android.R.id.text1}: Display the contents of the NAME column in the ListView text views.

The general form of the SimpleCursorAdapter constructor looks like this:

SimpleCursorAdapter adapter = new SimpleCursorAdapter(Conctext context, int layout, Cursor cursor, String[] fromColumns, int[] toViews, int flags)

Context context: This is usually the current activity

int layout: How to display the data

Cursor cursor: The cursor you create – the cursor should include the _id column and the data you want to appear

fromColumns:Which columns in the cursor to match to which views

int flags: Used to determine the behavior of the cursor
The flags parameter is usually set to 0, which is the dfault.The alternativ is to seit to FLAG_REGITE_CONTENT_OBSERVER to regiest a content observer that will be notified whe the content changes – it can lead to memory leaks.

Any cursor you use with a cursor adapter MUST include the _id column or it wont work.

The cursor must stay open..

When you use a cursor adapter, the cursor adapter needs the curso to stay open in ase it needs to retreive more data from it.

An example:

  • The list view gets displayed on the screen.
    When the list is first displayed, it will be sized to fit the screen.Let’s say it has space to show five items.
  • The list view asks its adapter for the first five items.
  • The cursor adapter asks its cursor to read five rows from the database.
    No matter how many rows the database table contains, the cursor only needs to read the first five rows.
  • The user scrolls the list
    As the user scrolls the list, the adapter asks the cursor to read moremrows from the database.This works fine if the cursors still open. If not – it will not work.
  • So you need to close the sursor and database in the activitys onDestroy() method.
public void onDestroy(){
   super.onDestroy();
   cursor.close();
   db.close()
}

Leave a Reply

Your email address will not be published. Required fields are marked *