Android SQLite - Cursor & ContentValues

爷,独闯天下 提交于 2019-12-02 23:46:26

You can use the method cursorRowToContentValues(Cursor cursor, ContentValues values) of the DatabaseUtils class.

example

Cursor c = db.query(tableName, 
            tableColumn, 
            where, 
            whereArgs,
            groupBy,
            having,
            orderBy);

ArrayList<ContentValues> retVal = new ArrayList<ContentValues>();
ContentValues map;  
if(c.moveToFirst()) {       
   do {
        map = new ContentValues();
        DatabaseUtils.cursorRowToContentValues(c, map);                 
        retVal.add(map);
    } while(c.moveToNext());
}

c.close();  
gengkev

I wrote my own version of the DatabaseUtils.cursorRowToContentValues method that David-mu mentioned in order to avoid a bug with parsing booleans. It asks the Cursor to parse ints and floats based on the types in the SQL database, rather than parsing them when calling the methods in ContentValues.

public static ContentValues cursorRowToContentValues(Cursor cursor) {
    ContentValues values = new ContentValues();
    String[] columns = cursor.getColumnNames();
    int length = columns.length;
    for (int i = 0; i < length; i++) {
        switch (cursor.getType(i)) {
            case Cursor.FIELD_TYPE_NULL:
                values.putNull(columns[i]);
                break;
            case Cursor.FIELD_TYPE_INTEGER:
                values.put(columns[i], cursor.getLong(i));
                break;
            case Cursor.FIELD_TYPE_FLOAT:
                values.put(columns[i], cursor.getDouble(i));
                break;
            case Cursor.FIELD_TYPE_STRING:
                values.put(columns[i], cursor.getString(i));
                break;
            case Cursor.FIELD_TYPE_BLOB:
                values.put(columns[i], cursor.getBlob(i));
                break;
        }
    }
    return values;
}

You can go to thenewboston there's a tut for SQLite(and using ContentValues) from 111-124 :D

Anyway, the one that he taught about ContentValues is in the 117th

Good Luck :D

PS : But he also use a Cursor :)

No. You have to do that with cursor and old good query. I'd be happy if query could return a array of CV objects.

Nope, you have to use the Cursor.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!