FileDocCategorySizeDatePackage
DatabaseUtils.javaAPI DocAndroid 5.1 API54432Thu Mar 12 22:22:10 GMT 2015android.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
public static final int
STATEMENT_SELECT
One of the values returned by {@link #getSqlStatementType(String)}.
public static final int
STATEMENT_UPDATE
One of the values returned by {@link #getSqlStatementType(String)}.
public static final int
STATEMENT_ATTACH
One of the values returned by {@link #getSqlStatementType(String)}.
public static final int
STATEMENT_BEGIN
One of the values returned by {@link #getSqlStatementType(String)}.
public static final int
STATEMENT_COMMIT
One of the values returned by {@link #getSqlStatementType(String)}.
public static final int
STATEMENT_ABORT
One of the values returned by {@link #getSqlStatementType(String)}.
public static final int
STATEMENT_PRAGMA
One of the values returned by {@link #getSqlStatementType(String)}.
public static final int
STATEMENT_DDL
One of the values returned by {@link #getSqlStatementType(String)}.
public static final int
STATEMENT_UNPREPARED
One of the values returned by {@link #getSqlStatementType(String)}.
public static final int
STATEMENT_OTHER
One of the values returned by {@link #getSqlStatementType(String)}.
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 java.lang.String[]appendSelectionArgs(java.lang.String[] originalValues, java.lang.String[] newValues)
Appends one set of selection args to another. This is useful when adding a selection argument to a user provided set.

        if (originalValues == null || originalValues.length == 0) {
            return newValues;
        }
        String[] result = new String[originalValues.length + newValues.length ];
        System.arraycopy(originalValues, 0, result, 0, originalValues.length);
        System.arraycopy(newValues, 0, result, originalValues.length, newValues.length);
        return result;
    
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 android.os.ParcelFileDescriptorblobFileDescriptorForQuery(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 blob value in the first column of the first row.

return
A read-only file descriptor for a copy of the blob value.

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

return
A read-only file descriptor for a copy of the blob value.

        prog.bindAllArgsAsStrings(selectionArgs);
        return prog.simpleQueryForBlobFileDescriptor();
    
public static java.lang.StringconcatenateWhere(java.lang.String a, java.lang.String b)
Concatenates two SQL WHERE clauses, handling empty or null values.

        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 voidcursorDoubleToContentValuesIfPresent(Cursor cursor, android.content.ContentValues values, java.lang.String column)
Reads a Double out of a column in a Cursor and writes it to a ContentValues. Adds nothing to the ContentValues if the column isn't present or if its value is null.

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

        final int index = cursor.getColumnIndex(column);
        if (index != -1 && !cursor.isNull(index)) {
            values.put(column, cursor.getDouble(index));
        }
    
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 voidcursorFillWindow(Cursor cursor, int position, CursorWindow window)
Fills the specified cursor window by iterating over the contents of the cursor. The window is filled until the cursor is exhausted or the window runs out of space. The original position of the cursor is left unchanged by this operation.

param
cursor The cursor that contains the data to put in the window.
param
position The start position for filling the window.
param
window The window to fill.
hide

        if (position < 0 || position >= cursor.getCount()) {
            return;
        }
        final int oldPos = cursor.getPosition();
        final int numColumns = cursor.getColumnCount();
        window.clear();
        window.setStartPosition(position);
        window.setNumColumns(numColumns);
        if (cursor.moveToPosition(position)) {
            do {
                if (!window.allocRow()) {
                    break;
                }
                for (int i = 0; i < numColumns; i++) {
                    final int type = cursor.getType(i);
                    final boolean success;
                    switch (type) {
                        case Cursor.FIELD_TYPE_NULL:
                            success = window.putNull(position, i);
                            break;

                        case Cursor.FIELD_TYPE_INTEGER:
                            success = window.putLong(cursor.getLong(i), position, i);
                            break;

                        case Cursor.FIELD_TYPE_FLOAT:
                            success = window.putDouble(cursor.getDouble(i), position, i);
                            break;

                        case Cursor.FIELD_TYPE_BLOB: {
                            final byte[] value = cursor.getBlob(i);
                            success = value != null ? window.putBlob(value, position, i)
                                    : window.putNull(position, i);
                            break;
                        }

                        default: // assume value is convertible to String
                        case Cursor.FIELD_TYPE_STRING: {
                            final String value = cursor.getString(i);
                            success = value != null ? window.putString(value, position, i)
                                    : window.putNull(position, i);
                            break;
                        }
                    }
                    if (!success) {
                        window.freeLastRow();
                        break;
                    }
                }
                position += 1;
            } while (cursor.moveToNext());
        }
        cursor.moveToPosition(oldPos);
    
public static voidcursorFloatToContentValuesIfPresent(Cursor cursor, android.content.ContentValues values, java.lang.String column)
Reads a Float out of a column in a Cursor and writes it to a ContentValues. Adds nothing to the ContentValues if the column isn't present or if its value is null.

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

        final int index = cursor.getColumnIndex(column);
        if (index != -1 && !cursor.isNull(index)) {
            values.put(column, cursor.getFloat(index));
        }
    
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 voidcursorIntToContentValuesIfPresent(Cursor cursor, android.content.ContentValues values, java.lang.String column)
Reads a Integer out of a column in a Cursor and writes it to a ContentValues. Adds nothing to the ContentValues if the column isn't present or if its value is null.

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

        final int index = cursor.getColumnIndex(column);
        if (index != -1 && !cursor.isNull(index)) {
            values.put(column, cursor.getInt(index));
        }
    
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 voidcursorLongToContentValuesIfPresent(Cursor cursor, android.content.ContentValues values, java.lang.String column)
Reads a Long out of a column in a Cursor and writes it to a ContentValues. Adds nothing to the ContentValues if the column isn't present or if its value is null.

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

        final int index = cursor.getColumnIndex(column);
        if (index != -1 && !cursor.isNull(index)) {
            values.put(column, cursor.getLong(index));
        }
    
public static intcursorPickFillWindowStartPosition(int cursorPosition, int cursorWindowCapacity)
Picks a start position for {@link Cursor#fillWindow} such that the window will contain the requested row and a useful range of rows around it. When the data set is too large to fit in a cursor window, seeking the cursor can become a very expensive operation since we have to run the query again when we move outside the bounds of the current window. We try to choose a start position for the cursor window such that 1/3 of the window's capacity is used to hold rows before the requested position and 2/3 of the window's capacity is used to hold rows after the requested position.

param
cursorPosition The row index of the row we want to get.
param
cursorWindowCapacity The estimated number of rows that can fit in a cursor window, or 0 if unknown.
return
The recommended start position, always less than or equal to the requested row.
hide

        return Math.max(cursorPosition - cursorWindowCapacity / 3, 0);
    
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 voidcursorShortToContentValuesIfPresent(Cursor cursor, android.content.ContentValues values, java.lang.String column)
Reads a Short out of a column in a Cursor and writes it to a ContentValues. Adds nothing to the ContentValues if the column isn't present or if its value is null.

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

        final int index = cursor.getColumnIndex(column);
        if (index != -1 && !cursor.isNull(index)) {
            values.put(column, cursor.getShort(index));
        }
    
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 voidcursorStringToContentValuesIfPresent(Cursor cursor, android.content.ContentValues values, java.lang.String column)
Reads a String out of a column in a Cursor and writes it to a ContentValues. Adds nothing to the ContentValues if the column isn't present or if its value is null.

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

        final int index = cursor.getColumnIndex(column);
        if (index != -1 && !cursor.isNull(index)) {
            values.put(column, cursor.getString(index));
        }
    
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 intfindRowIdColumnIndex(java.lang.String[] columnNames)
Returns column index of "_id" column, or -1 if not found.

hide

        int length = columnNames.length;
        for (int i = 0; i < length; i++) {
            if (columnNames[i].equals("_id")) {
                return i;
            }
        }
        return -1;
    
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 intgetSqlStatementType(java.lang.String sql)
Returns one of the following which represent the type of the given SQL statement.
  1. {@link #STATEMENT_SELECT}
  2. {@link #STATEMENT_UPDATE}
  3. {@link #STATEMENT_ATTACH}
  4. {@link #STATEMENT_BEGIN}
  5. {@link #STATEMENT_COMMIT}
  6. {@link #STATEMENT_ABORT}
  7. {@link #STATEMENT_OTHER}

param
sql the SQL statement whose type is returned by this method
return
one of the values listed above

        sql = sql.trim();
        if (sql.length() < 3) {
            return STATEMENT_OTHER;
        }
        String prefixSql = sql.substring(0, 3).toUpperCase(Locale.ROOT);
        if (prefixSql.equals("SEL")) {
            return STATEMENT_SELECT;
        } else if (prefixSql.equals("INS") ||
                prefixSql.equals("UPD") ||
                prefixSql.equals("REP") ||
                prefixSql.equals("DEL")) {
            return STATEMENT_UPDATE;
        } else if (prefixSql.equals("ATT")) {
            return STATEMENT_ATTACH;
        } else if (prefixSql.equals("COM")) {
            return STATEMENT_COMMIT;
        } else if (prefixSql.equals("END")) {
            return STATEMENT_COMMIT;
        } else if (prefixSql.equals("ROL")) {
            return STATEMENT_ABORT;
        } else if (prefixSql.equals("BEG")) {
            return STATEMENT_BEGIN;
        } else if (prefixSql.equals("PRA")) {
            return STATEMENT_PRAGMA;
        } else if (prefixSql.equals("CRE") || prefixSql.equals("DRO") ||
                prefixSql.equals("ALT")) {
            return STATEMENT_DDL;
        } else if (prefixSql.equals("ANA") || prefixSql.equals("DET")) {
            return STATEMENT_UNPREPARED;
        }
        return STATEMENT_OTHER;
    
public static intgetTypeOfObject(java.lang.Object obj)
Returns data type of the given object's value.

Returned values are

  • {@link Cursor#FIELD_TYPE_NULL}
  • {@link Cursor#FIELD_TYPE_INTEGER}
  • {@link Cursor#FIELD_TYPE_FLOAT}
  • {@link Cursor#FIELD_TYPE_STRING}
  • {@link Cursor#FIELD_TYPE_BLOB}

param
obj the object whose value type is to be returned
return
object value type
hide

        if (obj == null) {
            return Cursor.FIELD_TYPE_NULL;
        } else if (obj instanceof byte[]) {
            return Cursor.FIELD_TYPE_BLOB;
        } else if (obj instanceof Float || obj instanceof Double) {
            return Cursor.FIELD_TYPE_FLOAT;
        } else if (obj instanceof Long || obj instanceof Integer
                || obj instanceof Short || obj instanceof Byte) {
            return Cursor.FIELD_TYPE_INTEGER;
        } else {
            return Cursor.FIELD_TYPE_STRING;
        }
    
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.

        prog.bindAllArgsAsStrings(selectionArgs);
        return prog.simpleQueryForLong();
    
public static booleanqueryIsEmpty(android.database.sqlite.SQLiteDatabase db, java.lang.String table)
Query the table to check whether a table is empty or not

param
db the database the table is in
param
table the name of the table to query
return
True if the table is empty
hide

        long isEmpty = longForQuery(db, "select exists(select 1 from " + table + ")", null);
        return isEmpty == 0;
    
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

        return queryNumEntries(db, table, null, null);
    
public static longqueryNumEntries(android.database.sqlite.SQLiteDatabase db, java.lang.String table, java.lang.String selection)
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
param
selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will count all rows for the given table
return
the number of rows in the table filtered by the selection

        return queryNumEntries(db, table, selection, null);
    
public static longqueryNumEntries(android.database.sqlite.SQLiteDatabase db, java.lang.String table, java.lang.String selection, java.lang.String[] selectionArgs)
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
param
selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will count all rows for the given table
param
selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
return
the number of rows in the table filtered by the selection

        String s = (!TextUtils.isEmpty(selection)) ? " where " + selection : "";
        return longForQuery(db, "select count(*) from " + table + s,
                    selectionArgs);
    
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.readExceptionCode();
        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);
            case 11:
                throw new OperationCanceledException(msg);
            default:
                reply.readException(code, msg);
        }
    
public static voidreadExceptionWithFileNotFoundExceptionFromParcel(android.os.Parcel reply)

        int code = reply.readExceptionCode();
        if (code == 0) return;
        String msg = reply.readString();
        if (code == 1) {
            throw new FileNotFoundException(msg);
        } else {
            DatabaseUtils.readExceptionFromParcel(reply, msg, code);
        }
    
public static voidreadExceptionWithOperationApplicationExceptionFromParcel(android.os.Parcel reply)

        int code = reply.readExceptionCode();
        if (code == 0) return;
        String msg = reply.readString();
        if (code == 10) {
            throw new OperationApplicationException(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.

        prog.bindAllArgsAsStrings(selectionArgs);
        return prog.simpleQueryForString();
    
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 if (e instanceof OperationApplicationException) {
            code = 10;
        } else if (e instanceof OperationCanceledException) {
            code = 11;
            logException = false;
        } 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);
        }