Java Code Examples for android.database.sqlite.SQLiteStatement#close()

The following examples show how to use android.database.sqlite.SQLiteStatement#close() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private void upgradeScreenTimeoutFromNever(SQLiteDatabase db) {
    // See if the timeout is -1 (for "Never").
    Cursor c = db.query(TABLE_SYSTEM, new String[] { "_id", "value" }, "name=? AND value=?",
            new String[] { Settings.System.SCREEN_OFF_TIMEOUT, "-1" },
            null, null, null);

    SQLiteStatement stmt = null;
    if (c.getCount() > 0) {
        c.close();
        try {
            stmt = db.compileStatement("INSERT OR REPLACE INTO system(name,value)"
                    + " VALUES(?,?);");

            // Set the timeout to 30 minutes in milliseconds
            loadSetting(stmt, Settings.System.SCREEN_OFF_TIMEOUT,
                    Integer.toString(30 * 60 * 1000));
        } finally {
            if (stmt != null) stmt.close();
        }
    } else {
        c.close();
    }
}
 
Example 2
Source Project: android-sdk   File: GeofenceStorage.java    License: MIT License 6 votes vote down vote up
public void updateFences(List<String> fences) {
    SQLiteStatement stmt = null;
    try {
        long start = System.currentTimeMillis();
        db.beginTransaction();
        db.execSQL("DELETE FROM " + DBHelper.TABLE_GEOFENCES);
        stmt = db.compileStatement(
                "INSERT OR IGNORE INTO " + DBHelper.TABLE_GEOFENCES + " (" + DBHelper.TG_FENCE + ") VALUES (?)"
        );
        for (String fence : fences) {
            stmt.clearBindings();
            stmt.bindString(1, fence);
            stmt.executeInsert();
        }
        db.setTransactionSuccessful();
        count = fences.size();
        Logger.log.geofence("Saved "+fences.size()+" in "+(System.currentTimeMillis() - start) + " ms");
    } catch (SQLException ex) {
        Logger.log.geofenceError("Storage error", ex);
    } finally {
        if (stmt != null) {
            stmt.close();
        }
        db.endTransaction();
    }
}
 
Example 3
Source Project: tedroid   File: SQLiteTemplate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Ejecuta varias sentencias SQL (INSERT, UPDATE, DELETE, etc.) en la base de datos usando una
 * misma transacción.
 * 
 * @param sqls las sentencias SQL a ejecutar.
 */
void batchExecute(String[] sqls) {
    SQLiteDatabase database = null;
    try {
        database = databaseHelper.getWritableDatabase();
        database.beginTransaction();
        for (String sql : sqls) {
            SQLiteStatement statement = database.compileStatement(sql);
            statement.execute();
            statement.close();
        }
        database.setTransactionSuccessful();
    } catch (Exception ex) {
        Log.e(TAG, "Couldn't execute batch " + Arrays.deepToString(sqls), ex);
    } finally {
        SQLiteUtils.endTransaction(database);
        SQLiteUtils.close(database);
    }
}
 
Example 4
Source Project: beacons-android   File: Storage.java    License: Apache License 2.0 6 votes vote down vote up
private void migrateIBeaconItems(SQLiteDatabase db) {
    SQLiteStatement updateStatement = createUpdater(db, "d0", "d1", "d2");
    Cursor cursor = db.rawQuery("SELECT rowid, uuid, maj, min FROM " + IBEACONS_TABLE, null);
    while (cursor.moveToNext()) {
        updateStatement.bindLong(1, cursor.getLong(0));
        updateStatement.bindBlob(2, Base64.decode(cursor.getString(1), Base64.DEFAULT));
        updateStatement.bindLong(3, cursor.getInt(2));
        updateStatement.bindLong(4, cursor.getInt(3));

        executeSafeUpdateOrDelete(updateStatement);
    }
    cursor.close();
    updateStatement.close();

    db.execSQL("DROP TABLE " + IBEACONS_TABLE);
}
 
Example 5
Source Project: twitt4droid   File: SQLiteTemplate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Submits a batch of commands to the database for execution..
 * 
 * @param sqls SQLs to execute.
 */
void batchExecute(String[] sqls) {
    SQLiteDatabase database = null;
    try {
        database = databaseHelper.getWritableDatabase();
        database.beginTransaction();
        for (String sql : sqls) {
            SQLiteStatement statement = database.compileStatement(sql);
            statement.execute();
            statement.close();
        }
        database.setTransactionSuccessful();
    } catch (Exception ex) {
        Log.e(TAG, "Couldn't execute batch " + Arrays.deepToString(sqls), ex);
    } finally {
        SQLiteUtils.endTransaction(database);
        SQLiteUtils.close(database);
    }
}
 
Example 6
private void loadVibrateWhenRingingSetting(SQLiteDatabase db) {
    // The default should be off. VIBRATE_SETTING_ONLY_SILENT should also be ignored here.
    // Phone app should separately check whether AudioManager#getRingerMode() returns
    // RINGER_MODE_VIBRATE, with which the device should vibrate anyway.
    int vibrateSetting = getIntValueFromSystem(db, Settings.System.VIBRATE_ON,
            AudioManager.VIBRATE_SETTING_OFF);
    boolean vibrateWhenRinging = ((vibrateSetting & 3) == AudioManager.VIBRATE_SETTING_ON);

    SQLiteStatement stmt = null;
    try {
        stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
                + " VALUES(?,?);");
        loadSetting(stmt, Settings.System.VIBRATE_WHEN_RINGING, vibrateWhenRinging ? 1 : 0);
    } finally {
        if (stmt != null) stmt.close();
    }
}
 
Example 7
Source Project: android_9.0.0_r45   File: DatabaseUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to run the query on the db and return the value in the
 * first column of the first row.
 */
public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs) {
    SQLiteStatement prog = db.compileStatement(query);
    try {
        return longForQuery(prog, selectionArgs);
    } finally {
        prog.close();
    }
}
 
Example 8
/**
 * Set the end timestamp of the log.
 *
 * @param logId        the id of the log.
 * @param endTimestamp the end UTC timestamp.
 * @throws IOException
 */
public void setEndTs(long logId, long endTimestamp) throws IOException {
    SQLiteDatabase sqliteDatabase = GeopaparazziApplication.getInstance().getDatabase();
    try {
        sqliteDatabase.beginTransaction();

        StringBuilder sb = new StringBuilder();
        sb = new StringBuilder();
        sb.append("UPDATE ");
        sb.append(TABLE_GPSLOGS);
        sb.append(" SET ");
        sb.append(GpsLogsTableFields.COLUMN_LOG_ENDTS.getFieldName()).append("=").append(endTimestamp);
        sb.append(" WHERE ").append(GpsLogsTableFields.COLUMN_ID.getFieldName()).append("=").append(logId);

        String query = sb.toString();
        if (GPLog.LOG_HEAVY)
            GPLog.addLogEntry("DAOGPSLOG", query);
        SQLiteStatement updateEndTsStmt = sqliteDatabase.compileStatement(query);
        updateEndTsStmt.execute();
        updateEndTsStmt.close();

        sqliteDatabase.setTransactionSuccessful();
    } catch (Exception e) {
        GPLog.error("DAOGPSLOG", e.getLocalizedMessage(), e);
        throw new IOException(e.getLocalizedMessage());
    } finally {
        sqliteDatabase.endTransaction();
    }
}
 
Example 9
Source Project: squidb   File: SQLiteDatabaseAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public long simpleQueryForLong(String sql, Object[] bindArgs) {
    SQLiteStatement statement = null;
    try {
        statement = db.compileStatement(sql);
        SquidCursorFactory.bindArgumentsToProgram(statement, bindArgs);
        return statement.simpleQueryForLong();
    } finally {
        if (statement != null) {
            statement.close();
        }
    }
}
 
Example 10
@Override
public void execute(String sql, Object... params) throws IOException {
    try {
        SQLiteStatement s = db.compileStatement(sql);
        for (int i = 0; i < params.length; i++) {
            Object p = params[i];
            if(p == null){
                s.bindNull(i + 1);
            }else{
                if(p instanceof String){
                    s.bindString(i + 1, (String)p);                    
                }else if(p instanceof byte[]){
                    s.bindBlob(i + 1, (byte [])p);
                }else if(p instanceof Double){
                    s.bindDouble(i + 1, ((Double)p).doubleValue());
                } else if(p instanceof Long){
                    s.bindLong(i + 1, ((Long)p).longValue());
                } else if(p instanceof Integer){
                    s.bindLong(i + 1, ((Integer)p).intValue());
                } else {
                    if(p != null) {
                        s.bindString(i + 1, p.toString());
                    }
                }
            }
        }
        s.execute();
        s.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
    
}
 
Example 11
Source Project: weex-uikit   File: DefaultWXStorage.java    License: MIT License 5 votes vote down vote up
private boolean performSetItem(String key, String value, boolean isPersistent, boolean allowRetryWhenFull) {
    SQLiteDatabase database = mDatabaseSupplier.getDatabase();
    if (database == null) {
        return false;
    }

    WXLogUtils.d(WXSQLiteOpenHelper.TAG_STORAGE, "set k-v to storage(key:" + key + ",value:" + value + ",isPersistent:" + isPersistent + ",allowRetry:" + allowRetryWhenFull + ")");
    String sql = "INSERT OR REPLACE INTO " + WXSQLiteOpenHelper.TABLE_STORAGE + " VALUES (?,?,?,?);";
    SQLiteStatement statement = null;
    String timeStamp = WXSQLiteOpenHelper.sDateFormatter.format(new Date());
    try {
        statement = database.compileStatement(sql);
        statement.clearBindings();
        statement.bindString(1, key);
        statement.bindString(2, value);
        statement.bindString(3, timeStamp);
        statement.bindLong(4, isPersistent ? 1 : 0);
        statement.execute();
        return true;
    } catch (Exception e) {
        WXLogUtils.e(WXSQLiteOpenHelper.TAG_STORAGE, "DefaultWXStorage occurred an exception when execute setItem :" + e.getMessage());
        if (e instanceof SQLiteFullException) {
            if (allowRetryWhenFull && trimToSize()) {
                //try again
                //setItem/setItemPersistent method only allow try once when occurred a sqliteFullException.
                WXLogUtils.d(WXSQLiteOpenHelper.TAG_STORAGE, "retry set k-v to storage(key:" + key + ",value:" + value + ")");
                return performSetItem(key, value, isPersistent, false);
            }
        }

        return false;
    } finally {
        if(statement != null) {
            statement.close();
        }
    }
}
 
Example 12
public void log(String url, String req, String resp) {
    SQLiteDatabase db = null;
    SQLiteStatement statement;
    long timestamp;
    try {
        db = getWritableDatabase();
        db.beginTransaction();
        statement = db.compileStatement("INSERT INTO ".concat(packetlog_table_name).concat(" (timestamp, url, type, data) values (?, ?, ?, ?)"));

        timestamp = System.currentTimeMillis();
        statement.bindAllArgsAsStrings(new String[]{String.valueOf(timestamp), url, REQUEST, req});
        statement.execute();

        timestamp = System.currentTimeMillis();
        statement.bindAllArgsAsStrings(new String[]{String.valueOf(timestamp), url, RESPONSE, resp});
        statement.execute();

        statement.close();
        db.setTransactionSuccessful();
    } catch (RuntimeException e) {
        e.printStackTrace();
    } finally {
        if (db != null) {
            db.endTransaction();
        }
    }
}
 
Example 13
/**
 * Move any settings with the given prefixes from the source table to the
 * destination table.
 */
private void movePrefixedSettingsToNewTable(
        SQLiteDatabase db, String sourceTable, String destTable, String[] prefixesToMove) {
    SQLiteStatement insertStmt = null;
    SQLiteStatement deleteStmt = null;

    db.beginTransaction();
    try {
        insertStmt = db.compileStatement("INSERT INTO " + destTable
                + " (name,value) SELECT name,value FROM " + sourceTable
                + " WHERE substr(name,0,?)=?");
        deleteStmt = db.compileStatement(
                "DELETE FROM " + sourceTable + " WHERE substr(name,0,?)=?");

        for (String prefix : prefixesToMove) {
            insertStmt.bindLong(1, prefix.length() + 1);
            insertStmt.bindString(2, prefix);
            insertStmt.execute();

            deleteStmt.bindLong(1, prefix.length() + 1);
            deleteStmt.bindString(2, prefix);
            deleteStmt.execute();
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        if (insertStmt != null) {
            insertStmt.close();
        }
        if (deleteStmt != null) {
            deleteStmt.close();
        }
    }
}
 
Example 14
@Override
public void execute(String sql, String[] params) throws IOException {
    try {
        SQLiteStatement s = db.compileStatement(sql);
        for (int i = 0; i < params.length; i++) {
            String p = params[i];
            s.bindString(i + 1, p);
        }
        s.execute();
        s.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}
 
Example 15
public void writePreference(String className, long number, int priority, int usageQuantity) {
    Log.d("LaunchablePrefs", "writePreference running");
    final SQLiteDatabase db = getWritableDatabase();
    final SQLiteStatement countStatement = db.compileStatement(String.format(
            "SELECT COUNT(*) FROM %s WHERE %s = ?", TABLE_NAME,
            KEY_CLASSNAME));
    countStatement.bindString(1, className);
    final long count = countStatement.simpleQueryForLong();
    countStatement.close();
    final SQLiteStatement statement;
    if (count == 0) {
        statement = db.compileStatement("INSERT INTO "
                + TABLE_NAME + " (" + KEY_CLASSNAME + ", "
                + KEY_LASTLAUNCHTIMESTAMP + "," + KEY_FAVORITE + "," + KEY_USAGEQUANTIY + ") VALUES(?,?,?,?)");
        statement.bindString(1, className);
        statement.bindLong(2, number);
        statement.bindLong(3, priority);
        statement.bindLong(4, usageQuantity);
    } else {
        statement = db.compileStatement("UPDATE "
                + TABLE_NAME + " SET " + KEY_LASTLAUNCHTIMESTAMP + "=? , " + KEY_FAVORITE + "=? , " + KEY_USAGEQUANTIY + "=? WHERE "
                + KEY_CLASSNAME + "=?");
        statement.bindLong(1, number);
        statement.bindLong(2, priority);
        statement.bindLong(3, usageQuantity);
        statement.bindString(4, className);
    }
    statement.executeInsert();
    statement.close();
    db.close();
}
 
Example 16
Source Project: squidb   File: SQLiteDatabaseAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int executeUpdateDelete(String sql, Object[] bindArgs) {
    SQLiteStatement statement = null;
    try {
        statement = db.compileStatement(sql);
        SquidCursorFactory.bindArgumentsToProgram(statement, bindArgs);
        return statement.executeUpdateDelete();
    } finally {
        if (statement != null) {
            statement.close();
        }
    }
}
 
Example 17
/**
 * We can't use IOUtils here because older versions didn't implement Closeable.
 */
private void closeQuietly(SQLiteStatement statement) {
	if (statement != null) {
		statement.close();
	}
}
 
Example 18
/**
 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
 */
@Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
    db.beginTransaction();
    Cursor c = null;
    SQLiteStatement updateStmt = null;

    try {
        // Only consider the primary user as other users can't have a shortcut.
        long userSerial = getDefaultUserSerial();
        c = db.query(Favorites.TABLE_NAME, new String[] {
                Favorites._ID,
                Favorites.INTENT,
            }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
            null, null, null, null);

        updateStmt = db.compileStatement("UPDATE favorites SET itemType="
                + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");

        final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
        final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);

        while (c.moveToNext()) {
            String intentDescription = c.getString(intentIndex);
            Intent intent;
            try {
                intent = Intent.parseUri(intentDescription, 0);
            } catch (URISyntaxException e) {
                e.printStackTrace();
                continue;
            }

            if (!Utilities.isLauncherAppTarget(intent)) {
                continue;
            }

            long id = c.getLong(idIndex);
            updateStmt.bindLong(1, id);
            updateStmt.executeUpdateDelete();
        }
        db.setTransactionSuccessful();
    } catch (SQLException ex) {
        ex.printStackTrace();
    } finally {
        db.endTransaction();
        if (c != null) {
            c.close();
        }
        if (updateStmt != null) {
            updateStmt.close();
        }
    }
}
 
Example 19
private void loadSystemSettings(SQLiteDatabase db) {
      SQLiteStatement stmt = null;
String EnergyStar = SystemProperties.get("persist.hht.EnergyStar","false");
      try {
          stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
                  + " VALUES(?,?);");

          loadBooleanSetting(stmt, Settings.System.DIM_SCREEN,
                  R.bool.def_dim_screen);
	if("false".equals(EnergyStar))
           loadIntegerSetting(stmt, Settings.System.SCREEN_OFF_TIMEOUT,
                  R.integer.def_screen_off_timeout);
	else
		loadIntegerSetting(stmt, Settings.System.SCREEN_OFF_TIMEOUT,
                  R.integer.def_screen_off_timeout_EnergyStar);
         

          // Set default cdma DTMF type
          loadSetting(stmt, Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, 0);

          // Set default hearing aid
          loadSetting(stmt, Settings.System.HEARING_AID, 0);

          // Set default tty mode
          loadSetting(stmt, Settings.System.TTY_MODE, 0);

          loadIntegerSetting(stmt, Settings.System.SCREEN_BRIGHTNESS,
                  R.integer.def_screen_brightness);

          loadBooleanSetting(stmt, Settings.System.SCREEN_BRIGHTNESS_MODE,
                  R.bool.def_screen_brightness_automatic_mode);

          loadDefaultAnimationSettings(stmt);

          loadBooleanSetting(stmt, Settings.System.ACCELEROMETER_ROTATION,
                  R.bool.def_accelerometer_rotation);

          loadDefaultHapticSettings(stmt);

          loadBooleanSetting(stmt, Settings.System.NOTIFICATION_LIGHT_PULSE,
                  R.bool.def_notification_pulse);

          loadUISoundEffectsSettings(stmt);

          loadIntegerSetting(stmt, Settings.System.POINTER_SPEED,
                  R.integer.def_pointer_speed);
      } finally {
          if (stmt != null) stmt.close();
      }
  }
 
Example 20
/**
 * Loads the default volume levels. It is actually inserting the index of
 * the volume array for each of the volume controls.
 *
 * @param db the database to insert the volume levels into
 */
private void loadVolumeLevels(SQLiteDatabase db) {
    SQLiteStatement stmt = null;
    try {
        stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
                + " VALUES(?,?);");

        loadSetting(stmt, Settings.System.VOLUME_MUSIC,
                AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_MUSIC]);
        loadSetting(stmt, Settings.System.VOLUME_RING,
                AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_RING]);
        loadSetting(stmt, Settings.System.VOLUME_SYSTEM,
                AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_SYSTEM]);
        loadSetting(
                stmt,
                Settings.System.VOLUME_VOICE,
                AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_VOICE_CALL]);
        loadSetting(stmt, Settings.System.VOLUME_ALARM,
                AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_ALARM]);
        loadSetting(
                stmt,
                Settings.System.VOLUME_NOTIFICATION,
                AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_NOTIFICATION]);
        loadSetting(
                stmt,
                Settings.System.VOLUME_BLUETOOTH_SCO,
                AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_BLUETOOTH_SCO]);

        // By default:
        // - ringtones, notification, system and music streams are affected by ringer mode
        // on non voice capable devices (tablets)
        // - ringtones, notification and system streams are affected by ringer mode
        // on voice capable devices (phones)
        int ringerModeAffectedStreams = (1 << AudioManager.STREAM_RING) |
                                        (1 << AudioManager.STREAM_NOTIFICATION) |
                                        (1 << AudioManager.STREAM_SYSTEM) |
                                        (1 << AudioManager.STREAM_SYSTEM_ENFORCED);
        if (!mContext.getResources().getBoolean(
                com.android.internal.R.bool.config_voice_capable)) {
            ringerModeAffectedStreams |= (1 << AudioManager.STREAM_MUSIC);
        }
        loadSetting(stmt, Settings.System.MODE_RINGER_STREAMS_AFFECTED,
                ringerModeAffectedStreams);

        loadSetting(stmt, Settings.System.MUTE_STREAMS_AFFECTED,
                ((1 << AudioManager.STREAM_MUSIC) |
                 (1 << AudioManager.STREAM_RING) |
                 (1 << AudioManager.STREAM_NOTIFICATION) |
                 (1 << AudioManager.STREAM_SYSTEM)));
    } finally {
        if (stmt != null) stmt.close();
    }

    loadVibrateWhenRingingSetting(db);
}