FileDocCategorySizeDatePackage
DatabaseUtils.javaAPI DocAndroid 1.5 API37027Wed May 06 22:41:54 BST 2009android.database

DatabaseUtils

public class DatabaseUtils extends Object
Static utility methods for dealing with databases and {@link Cursor}s.

Fields Summary
private static final String
TAG
private static final boolean
DEBUG
private static final boolean
LOCAL_LOGV
private static final String[]
countProjection
private static Collator
mColl
Constructors Summary
Methods Summary
public static voidappendEscapedSQLString(java.lang.StringBuilder sb, java.lang.String sqlString)
Appends an SQL string to the given StringBuilder, including the opening and closing single quotes. Any single quotes internal to sqlString will be escaped. This method is deprecated because we want to encourage everyone to use the "?" binding form. However, when implementing a ContentProvider, one may want to add WHERE clauses that were not provided by the caller. Since "?" is a positional form, using it in this case could break the caller because the indexes would be shifted to accomodate the ContentProvider's internal bindings. In that case, it may be necessary to construct a WHERE clause manually. This method is useful for those cases.

param
sb the StringBuilder that the SQL string will be appended to
param
sqlString the raw string to be appended, which may contain single quotes

        sb.append('\'");
        if (sqlString.indexOf('\'") != -1) {
            int length = sqlString.length();
            for (int i = 0; i < length; i++) {
                char c = sqlString.charAt(i);
                if (c == '\'") {
                    sb.append('\'");
                }
                sb.append(c);
            }
        } else
            sb.append(sqlString);
        sb.append('\'");
    
public static final voidappendValueToSql(java.lang.StringBuilder sql, java.lang.Object value)
Appends an Object to an SQL string with the proper escaping, etc.

        if (value == null) {
            sql.append("NULL");
        } else if (value instanceof Boolean) {
            Boolean bool = (Boolean)value;
            if (bool) {
                sql.append('1");
            } else {
                sql.append('0");
            }
        } else {
            appendEscapedSQLString(sql, value.toString());
        }
    
public static voidbindObjectToProgram(android.database.sqlite.SQLiteProgram prog, int index, java.lang.Object value)
Binds the given Object to the given SQLiteProgram using the proper typing. For example, bind numbers as longs/doubles, and everything else as a string by call toString() on it.

param
prog the program to bind the object to
param
index the 1-based index to bind at
param
value the value to bind

        if (value == null) {
            prog.bindNull(index);
        } else if (value instanceof Double || value instanceof Float) {
            prog.bindDouble(index, ((Number)value).doubleValue());
        } else if (value instanceof Number) {
            prog.bindLong(index, ((Number)value).longValue());
        } else if (value instanceof Boolean) {
            Boolean bool = (Boolean)value;
            if (bool) {
                prog.bindLong(index, 1);
            } else {
                prog.bindLong(index, 0);
            }
        } else if (value instanceof byte[]){
            prog.bindBlob(index, (byte[]) value);
        } else {
            prog.bindString(index, value.toString());
        }
    
public static java.lang.StringconcatenateWhere(java.lang.String a, java.lang.String b)
Concatenates two SQL WHERE clauses, handling empty or null values.

hide

        if (TextUtils.isEmpty(a)) {
            return b;
        }
        if (TextUtils.isEmpty(b)) {
            return a;
        }
            
        return "(" + a + ") AND (" + b + ")";
    
public static voidcreateDbFromSqlStatements(android.content.Context context, java.lang.String dbName, int dbVersion, java.lang.String sqlStatements)
Creates a db and populates it with the sql statements in sqlStatements.

param
context the context to use to create the db
param
dbName the name of the db to create
param
dbVersion the version to set on the db
param
sqlStatements the statements to use to populate the db. This should be a single string of the form returned by sqlite3's .dump command (statements separated by semicolons)

        SQLiteDatabase db = context.openOrCreateDatabase(dbName, 0, null);
        // TODO: this is not quite safe since it assumes that all semicolons at the end of a line
        // terminate statements. It is possible that a text field contains ;\n. We will have to fix
        // this if that turns out to be a problem.
        String[] statements = TextUtils.split(sqlStatements, ";\n");
        for (String statement : statements) {
            if (TextUtils.isEmpty(statement)) continue;
            db.execSQL(statement);
        }
        db.setVersion(dbVersion);
        db.close();
    
public static voidcursorDoubleToContentValues(Cursor cursor, java.lang.String field, android.content.ContentValues values, java.lang.String key)
Reads a Double out of a field in a Cursor and writes it to a Map.

param
cursor The cursor to read from
param
field The REAL field to read
param
values The {@link ContentValues} to put the value into
param
key The key to store the value with in the map

        int colIndex = cursor.getColumnIndex(field);
        if (!cursor.isNull(colIndex)) {
            values.put(key, cursor.getDouble(colIndex));
        } else {
            values.put(key, (Double) null);
        }
    
public static voidcursorDoubleToCursorValues(Cursor cursor, java.lang.String field, android.content.ContentValues values)
Reads a Double out of a field in a Cursor and writes it to a Map.

param
cursor The cursor to read from
param
field The REAL field to read
param
values The {@link ContentValues} to put the value into

        cursorDoubleToContentValues(cursor, field, values, field);
    
public static voidcursorIntToContentValues(Cursor cursor, java.lang.String field, android.content.ContentValues values)
Reads an Integer out of a field in a Cursor and writes it to a Map.

param
cursor The cursor to read from
param
field The INTEGER field to read
param
values The {@link ContentValues} to put the value into, with the field as the key

        cursorIntToContentValues(cursor, field, values, field);
    
public static voidcursorIntToContentValues(Cursor cursor, java.lang.String field, android.content.ContentValues values, java.lang.String key)
Reads a Integer out of a field in a Cursor and writes it to a Map.

param
cursor The cursor to read from
param
field The INTEGER field to read
param
values The {@link ContentValues} to put the value into, with the field as the key
param
key The key to store the value with in the map

        int colIndex = cursor.getColumnIndex(field);
        if (!cursor.isNull(colIndex)) {
            values.put(key, cursor.getInt(colIndex));
        } else {
            values.put(key, (Integer) null);
        }
    
public static voidcursorLongToContentValues(Cursor cursor, java.lang.String field, android.content.ContentValues values)
Reads a Long out of a field in a Cursor and writes it to a Map.

param
cursor The cursor to read from
param
field The INTEGER field to read
param
values The {@link ContentValues} to put the value into, with the field as the key

        cursorLongToContentValues(cursor, field, values, field);
    
public static voidcursorLongToContentValues(Cursor cursor, java.lang.String field, android.content.ContentValues values, java.lang.String key)
Reads a Long out of a field in a Cursor and writes it to a Map.

param
cursor The cursor to read from
param
field The INTEGER field to read
param
values The {@link ContentValues} to put the value into
param
key The key to store the value with in the map

        int colIndex = cursor.getColumnIndex(field);
        if (!cursor.isNull(colIndex)) {
            Long value = Long.valueOf(cursor.getLong(colIndex));
            values.put(key, value);
        } else {
            values.put(key, (Long) null);
        }
    
public static voidcursorRowToContentValues(Cursor cursor, android.content.ContentValues values)
Read the entire contents of a cursor row and store them in a ContentValues.

param
cursor the cursor to read from.
param
values the {@link ContentValues} to put the row into.

        AbstractWindowedCursor awc =
                (cursor instanceof AbstractWindowedCursor) ? (AbstractWindowedCursor) cursor : null;

        String[] columns = cursor.getColumnNames();
        int length = columns.length;
        for (int i = 0; i < length; i++) {
            if (awc != null && awc.isBlob(i)) {
                values.put(columns[i], cursor.getBlob(i));
            } else {
                values.put(columns[i], cursor.getString(i));
            }
        }
    
public static voidcursorStringToContentValues(Cursor cursor, java.lang.String field, android.content.ContentValues values)
Reads a String out of a field in a Cursor and writes it to a Map.

param
cursor The cursor to read from
param
field The TEXT field to read
param
values The {@link ContentValues} to put the value into, with the field as the key

        cursorStringToContentValues(cursor, field, values, field);
    
public static voidcursorStringToContentValues(Cursor cursor, java.lang.String field, android.content.ContentValues values, java.lang.String key)
Reads a String out of a field in a Cursor and writes it to a Map.

param
cursor The cursor to read from
param
field The TEXT field to read
param
values The {@link ContentValues} to put the value into, with the field as the key
param
key The key to store the value with in the map

        values.put(key, cursor.getString(cursor.getColumnIndexOrThrow(field)));
    
public static voidcursorStringToInsertHelper(Cursor cursor, java.lang.String field, android.database.DatabaseUtils$InsertHelper inserter, int index)
Reads a String out of a field in a Cursor and writes it to an InsertHelper.

param
cursor The cursor to read from
param
field The TEXT field to read
param
inserter The InsertHelper to bind into
param
index the index of the bind entry in the InsertHelper

        inserter.bind(index, cursor.getString(cursor.getColumnIndexOrThrow(field)));
    
public static voiddumpCurrentRow(Cursor cursor)
Prints the contents of a Cursor's current row to System.out.

param
cursor the cursor to print from

        dumpCurrentRow(cursor, System.out);
    
public static voiddumpCurrentRow(Cursor cursor, java.io.PrintStream stream)
Prints the contents of a Cursor's current row to a PrintSteam.

param
cursor the cursor to print
param
stream the stream to print to

        String[] cols = cursor.getColumnNames();
        stream.println("" + cursor.getPosition() + " {");
        int length = cols.length;
        for (int i = 0; i< length; i++) {
            String value;
            try {
                value = cursor.getString(i);
            } catch (SQLiteException e) {
                // assume that if the getString threw this exception then the column is not
                // representable by a string, e.g. it is a BLOB.
                value = "<unprintable>";
            }
            stream.println("   " + cols[i] + '=" + value);
        }
        stream.println("}");
    
public static voiddumpCurrentRow(Cursor cursor, java.lang.StringBuilder sb)
Prints the contents of a Cursor's current row to a StringBuilder.

param
cursor the cursor to print
param
sb the StringBuilder to print to

        String[] cols = cursor.getColumnNames();
        sb.append("" + cursor.getPosition() + " {\n");
        int length = cols.length;
        for (int i = 0; i < length; i++) {
            String value;
            try {
                value = cursor.getString(i);
            } catch (SQLiteException e) {
                // assume that if the getString threw this exception then the column is not
                // representable by a string, e.g. it is a BLOB.
                value = "<unprintable>";
            }
            sb.append("   " + cols[i] + '=" + value + "\n");
        }
        sb.append("}\n");
    
public static java.lang.StringdumpCurrentRowToString(Cursor cursor)
Dump the contents of a Cursor's current row to a String.

param
cursor the cursor to print
return
a String that contains the dumped cursor row

        StringBuilder sb = new StringBuilder();
        dumpCurrentRow(cursor, sb);
        return sb.toString();
    
public static voiddumpCursor(Cursor cursor)
Prints the contents of a Cursor to System.out. The position is restored after printing.

param
cursor the cursor to print

    
                             
         
        dumpCursor(cursor, System.out);
    
public static voiddumpCursor(Cursor cursor, java.io.PrintStream stream)
Prints the contents of a Cursor to a PrintSteam. The position is restored after printing.

param
cursor the cursor to print
param
stream the stream to print to

        stream.println(">>>>> Dumping cursor " + cursor);
        if (cursor != null) {
            int startPos = cursor.getPosition();

            cursor.moveToPosition(-1);
            while (cursor.moveToNext()) {
                dumpCurrentRow(cursor, stream);
            }
            cursor.moveToPosition(startPos);
        }
        stream.println("<<<<<");
    
public static voiddumpCursor(Cursor cursor, java.lang.StringBuilder sb)
Prints the contents of a Cursor to a StringBuilder. The position is restored after printing.

param
cursor the cursor to print
param
sb the StringBuilder to print to

        sb.append(">>>>> Dumping cursor " + cursor + "\n");
        if (cursor != null) {
            int startPos = cursor.getPosition();

            cursor.moveToPosition(-1);
            while (cursor.moveToNext()) {
                dumpCurrentRow(cursor, sb);
            }
            cursor.moveToPosition(startPos);
        }
        sb.append("<<<<<\n");
    
public static java.lang.StringdumpCursorToString(Cursor cursor)
Prints the contents of a Cursor to a String. The position is restored after printing.

param
cursor the cursor to print
return
a String that contains the dumped cursor

        StringBuilder sb = new StringBuilder();
        dumpCursor(cursor, sb);
        return sb.toString();
    
public static java.lang.StringgetCollationKey(java.lang.String name)
return the collation key

param
name
return
the collation key

        byte [] arr = getCollationKeyInBytes(name);
        try {
            return new String(arr, 0, getKeyLen(arr), "ISO8859_1");
        } catch (Exception ex) {
            return "";
        }
    
private static byte[]getCollationKeyInBytes(java.lang.String name)

        if (mColl == null) {
            mColl = Collator.getInstance();
            mColl.setStrength(Collator.PRIMARY);
        }
        return mColl.getCollationKey(name).toByteArray();        
    
public static java.lang.StringgetHexCollationKey(java.lang.String name)
return the collation key in hex format

param
name
return
the collation key in hex format

        byte [] arr = getCollationKeyInBytes(name);
        char[] keys = Hex.encodeHex(arr);
        return new String(keys, 0, getKeyLen(arr) * 2);
    
private static intgetKeyLen(byte[] arr)

        if (arr[arr.length - 1] != 0) {
            return arr.length;
        } else {
            // remove zero "termination"
            return arr.length-1;
        }
    
public static longlongForQuery(android.database.sqlite.SQLiteDatabase db, java.lang.String query, java.lang.String[] selectionArgs)
Utility method to run the query on the db and return the value in the first column of the first row.

        SQLiteStatement prog = db.compileStatement(query);
        try {
            return longForQuery(prog, selectionArgs);
        } finally {
            prog.close();
        }
    
public static longlongForQuery(android.database.sqlite.SQLiteStatement prog, java.lang.String[] selectionArgs)
Utility method to run the pre-compiled query and return the value in the first column of the first row.

        if (selectionArgs != null) {
            int size = selectionArgs.length;
            for (int i = 0; i < size; i++) {
                bindObjectToProgram(prog, i + 1, selectionArgs[i]);
            }
        }
        long value = prog.simpleQueryForLong();
        return value;
    
public static longqueryNumEntries(android.database.sqlite.SQLiteDatabase db, java.lang.String table)
Query the table for the number of rows in the table.

param
db the database the table is in
param
table the name of the table to query
return
the number of rows in the table

        Cursor cursor = db.query(table, countProjection,
                null, null, null, null, null);
        cursor.moveToFirst();
        long count = cursor.getLong(0);
        cursor.deactivate();
        return count;
    
public static final voidreadExceptionFromParcel(android.os.Parcel reply)
Special function for reading an exception result from the header of a parcel, to be used after receiving the result of a transaction. This will throw the exception for you if it had been written to the Parcel, otherwise return and let you read the normal result data from the Parcel.

param
reply Parcel to read from
see
Parcel#writeNoException
see
Parcel#readException

        int code = reply.readInt();
        if (code == 0) return;
        String msg = reply.readString();
        DatabaseUtils.readExceptionFromParcel(reply, msg, code);
    
private static final voidreadExceptionFromParcel(android.os.Parcel reply, java.lang.String msg, int code)

        switch (code) {
            case 2:
                throw new IllegalArgumentException(msg);
            case 3:
                throw new UnsupportedOperationException(msg);
            case 4:
                throw new SQLiteAbortException(msg);
            case 5:
                throw new SQLiteConstraintException(msg);
            case 6:
                throw new SQLiteDatabaseCorruptException(msg);
            case 7:
                throw new SQLiteFullException(msg);
            case 8:
                throw new SQLiteDiskIOException(msg);
            case 9:
                throw new SQLiteException(msg);
            default:
                reply.readException(code, msg);
        }
    
public static voidreadExceptionWithFileNotFoundExceptionFromParcel(android.os.Parcel reply)

        int code = reply.readInt();
        if (code == 0) return;
        String msg = reply.readString();
        if (code == 1) {
            throw new FileNotFoundException(msg);
        } else {
            DatabaseUtils.readExceptionFromParcel(reply, msg, code);
        }
    
public static java.lang.StringsqlEscapeString(java.lang.String value)
SQL-escape a string.

        StringBuilder escaper = new StringBuilder();

        DatabaseUtils.appendEscapedSQLString(escaper, value);

        return escaper.toString();
    
public static java.lang.StringstringForQuery(android.database.sqlite.SQLiteDatabase db, java.lang.String query, java.lang.String[] selectionArgs)
Utility method to run the query on the db and return the value in the first column of the first row.

        SQLiteStatement prog = db.compileStatement(query);
        try {
            return stringForQuery(prog, selectionArgs);
        } finally {
            prog.close();
        }
    
public static java.lang.StringstringForQuery(android.database.sqlite.SQLiteStatement prog, java.lang.String[] selectionArgs)
Utility method to run the pre-compiled query and return the value in the first column of the first row.

        if (selectionArgs != null) {
            int size = selectionArgs.length;
            for (int i = 0; i < size; i++) {
                bindObjectToProgram(prog, i + 1, selectionArgs[i]);
            }
        }
        String value = prog.simpleQueryForString();
        return value;
    
public static final voidwriteExceptionToParcel(android.os.Parcel reply, java.lang.Exception e)
Special function for writing an exception result at the header of a parcel, to be used when returning an exception from a transaction. exception will be re-thrown by the function in another process

param
reply Parcel to write to
param
e The Exception to be written.
see
Parcel#writeNoException
see
Parcel#writeException


                                                           
            
        int code = 0;
        boolean logException = true;
        if (e instanceof FileNotFoundException) {
            code = 1;
            logException = false;
        } else if (e instanceof IllegalArgumentException) {
            code = 2;
        } else if (e instanceof UnsupportedOperationException) {
            code = 3;
        } else if (e instanceof SQLiteAbortException) {
            code = 4;
        } else if (e instanceof SQLiteConstraintException) {
            code = 5;
        } else if (e instanceof SQLiteDatabaseCorruptException) {
            code = 6;
        } else if (e instanceof SQLiteFullException) {
            code = 7;
        } else if (e instanceof SQLiteDiskIOException) {
            code = 8;
        } else if (e instanceof SQLiteException) {
            code = 9;
        } else {
            reply.writeException(e);
            Log.e(TAG, "Writing exception to parcel", e);
            return;
        }
        reply.writeInt(code);
        reply.writeString(e.getMessage());

        if (logException) {
            Log.e(TAG, "Writing exception to parcel", e);
        }