How to clone or freeze an Android database cursor

前端 未结 3 1001
再見小時候
再見小時候 2021-01-06 17:00

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 co

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-06 17:12

    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

提交回复
热议问题