I have a custom cursor adapter, and I would like to pass each 'row' of the cursor back to the application (via a registered callback which is working).
I know I could read each of the fields from the cursor and do it manually, but I would simply like to pass a 'frozen clone' of the cursor back. (Reading the fields in the adapter would require me to make several specialised versions of this class.)
Ideally I would like to pass back something with the same interface as Cursor, but which couldn't traverse the result set.
The queries return fewer than 20 rows, so space is not an issue.
I guess you have a cursor with 20 rows and now you want to invoke a method 20 times with a cursor that contains only one row. Here is how you can do this:
Cursor c = ...;// contains many rows
if(c.moveToFirst()){
String[] columns = c.getColumnNames();
while(!c.isAfterLast()){
MatrixCursor newCursor = new MatrixCursor(columns , 1);
MatrixCursor.RowBuilder b = newCursor.newRow();
for(String col: columns){
// in case all columns are of string type. But if they are
// different then see my comment below
b.add(c.getString(c.getColumnIndex(col)));
}
// invoke your listener here with newCursor
}
}
What if data type of columns is not String?
For API>=11: Just call getType()
method in for
loop and use switch
statement to invoke appropriate get method.
For API<11: Run another query similar to this PRAGMA table_info(my_table_name)
and then just fill a Map
of column name and type and use it in for loop. Here is how you can read this cursor https://stackoverflow.com/a/9354401/1112882