Iterate through rows from Sqlite-query

kakka47 picture kakka47 · Feb 7, 2011 · Viewed 67.8k times · Source

I have a table layout that I want to populate with the result from a database query. I use a select all and the query returns four rows of data.

I use this code to populate the TextViews inside the table rows.

Cursor c = null;
c = dh.getAlternative2();
startManagingCursor(c);
// the desired columns to be bound
String[] columns = new String[] {DataHelper.KEY_ALT};
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.name_entry};

SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, 
         R.layout.list_example_entry, c, columns, to);
this.setListAdapter(mAdapter);

I want to be able to separate the four different values of KEY_ALT, and choose where they go. I want them to populate four different TextViews instead of one in my example above.

How can I iterate through the resulting cursor?

Answer

happydude picture happydude · Oct 5, 2012

Cursor objects returned by database queries are positioned before the first entry, therefore iteration can be simplified to:

while (cursor.moveToNext()) {
    // Extract data.
}

Reference from SQLiteDatabase.