Cursor in Android
Cursors
Cursors are the ones that contain the result set of a query
made against a database in Android.
The Cursor class has an
API that allows an app to read (in a type-safe manner) the columns that were
returned from the query as well as iterate over the rows of the result set.
Once a cursor has been returned from a database query, App
needs to iterate over the result set and read the column data from the cursor
In order to get the columns and rows, we use the statement:
Int col = cursor.getColumnCount();
Int row = cursor.getCount();
In order to get the column names, we use:
String[] columnNames = cursor.getColumnNames();
Cursor cursor = database.query(TABLE_NAME, columnNames, null, null, null, null, null);
The Cursor class provides the following methods to
manipulate its internal position:
· boolean Cursor.move(int offset): Moves the position by the
given offset
· boolean Cursor.moveToFirst(): Moves the position to the
first row
· boolean Cursor.moveToLast(): Moves the position to the last
row
· boolean Cursor.moveToNext(): Moves the cursor to the next
row relative to the current position
· boolean Cursor.moveToPosition(int position): Moves the
cursor to the specified position
· Cursor.moveToPrevious(): Moves the cursor to the previous
row relative to the current position
SQLiteDatabase db = getDatabase(); String[] columns = {"first_name", "last_name", "id"}; Cursor cursor = db.query("people", columns, null, null, null, null, null); while(cursor.moveToNext()) { int index; index = cursor.getColumnIndexOrThrow("first_name"); String firstName = cursor.getString(index); index = cursor.getColumnIndexOrThrow("last_name"); String lastName = cursor.getString(index); index = cursor.getColumnIndexOrThrow("id"); long id = cursor.getLong(index); //... do something with data }
Comments
Post a Comment