Android SQLite - Cursor & ContentValues

2019-03-14 10:08发布

问题:

Is there any way to GET the ContentValues object from the SQLite? It's very useful, that we can insert ContentValues in DB, and it should be more useful to get the CV from there.

回答1:

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();  


回答2:

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;
}


回答3:

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 :)



回答4:

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.



回答5:

Nope, you have to use the Cursor.