There are two factors that need to be considered when retrieving data from a cursor; which row (position within the cursor) and then column and it's type.
To position the Cursor you use one of the Cursor's move
methods. These are :-
move
, which moves the cursor relevant to it's current position.
moveToFirst
moveToLast
moveToNext
moveToPosition
and
moveToPrevious
All return true if the move could be performed otherwise false.
A cursor can be empty and have no rows, so movetoFirst
would return false.
One of the more common usages is :-
while (cursor.moveToNext) {
.... cursor action(s) here.
}
A Cursor will initially be positioned to before the first row i.e. it's position is -1 and can be set using moveToPosition(-1)
.
The Cursor's getPosition
method will retrieve the current position, noting that the first row is position 0.
Column's in rows are accessed according to the offset (which column) and the Cursor's get????
(where ???? represents type) methods are used to retrieve the data from the row/column (there are other get.... methods e.g. getPosition
as above). The methods for retrieving the data are:-
getBlob
(retrieves a byte array).
getDouble
getFloat
getInt
getLong
getShort
getString
All take a single parameter, an integer that is the column's offset within the cursor (which is not necessarily the offset in the table).
You can use any on any type of data, with the exception of blobs. An attempt to use any, except getBlob
, on a BLOB will result in an exception.
However, the results, can vary e.g. if you use get
, for example assuming column with offset 0 contains *rumplestilskin then :-
cursor.getString(0)
will return rumplestiltskin
cursor.getDouble(0)
will return 0 as a double.
cursor.getInt(0)
will return 0 as a float.
- .....
In short, you should use the appropriate get method, otherwise the results could be confusing.
Hard coding column column offsets, often results in issues therefore it is generally better to use column names in conjunction with the Cursor's getColumnIndex
method. This takes a String, the column name, as a parameter and returns the offset of the column.
Applying the above to the question:-
Code that could be useful (i.e. it retrieves data) could be :-
Cursor csr = db.getData(myid);
while (csr.moveToNext) {
long id_of_the_row = csr.getLong(csr.getColumnIndex(yourDatabaseHelperClass.id));
}
Noting:-
if (moveToFirst(myid)) { .... }
could be considered more correct but assuming that just a single row exists bot moveToFirst and moveToNext, as coded, produce the same result.
- Assuming that the id column is an alias of the rowid, then rowid is stored as a long and should properly be extracted as a long.
- yourDatabaseHelperClass.id will not be correct, rather you would replace it with the class that extends SQLiteOpenHelper (the class that contains your
getData
method), it also assumes that variable id
has public
access.
Links that may be useful or of interest:-