List of usage examples for android.database.sqlite SQLiteDatabase endTransaction
public void endTransaction()
From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java
private void mergeDbs() { Log.d(LOG_TAG, "update received - juggling dbs"); // Get main database, attach temp db to it. SQLiteDatabase mainDb = dataService.getHelper().getWritableDatabase(); mainDb.execSQL("attach database ? as ka_temp", new Object[] { dataService.getDatabasePath("ka_temp").getAbsolutePath() }); mainDb.beginTransaction();/* w w w.j a v a 2 s . c om*/ try { // Maintain download status. String sql = "select max(download_status), dlm_id, youtube_id from video where download_status != ? group by youtube_id"; Cursor c = mainDb.rawQuery(sql, new String[] { "" + Video.DL_STATUS_NOT_STARTED }); Cursor c1; String[] videoIds = new String[c.getCount()]; int i = 0; while (c.moveToNext()) { String youtube_id = c.getString(c.getColumnIndex("youtube_id")); String download_status = c.getString(c.getColumnIndex("max(download_status)")); long dlm_id = c.getLong(c.getColumnIndex("dlm_id")); videoIds[i++] = youtube_id; ContentValues v = new ContentValues(); v.put("download_status", download_status); v.put("dlm_id", dlm_id); String[] idArg = new String[] { youtube_id }; mainDb.update("ka_temp.video", v, "youtube_id = ?", idArg); // cursor over parent topics of this video sql = "select ka_temp.topic._id from ka_temp.topic, ka_temp.topicvideo, ka_temp.video where ka_temp.video.youtube_id=? and ka_temp.topicvideo.video_id=ka_temp.video.readable_id and ka_temp.topicvideo.topic_id=ka_temp.topic._id"; c1 = mainDb.rawQuery(sql, idArg); Log.d(LOG_TAG, String.format("updating counts for %d topics", c1.getCount())); while (c1.moveToNext()) { String topicId = c1.getString(c1.getColumnIndex("_id")); DatabaseHelper.incrementDownloadedVideoCounts(mainDb, topicId, "ka_temp.topic"); } c1.close(); } c.close(); mainDb.execSQL("delete from topic"); mainDb.execSQL("insert into topic select * from ka_temp.topic"); mainDb.execSQL("delete from topicvideo"); mainDb.execSQL("insert into topicvideo select * from ka_temp.topicvideo"); mainDb.execSQL("delete from video"); mainDb.execSQL("insert into video select * from ka_temp.video"); mainDb.setTransactionSuccessful(); } finally { mainDb.endTransaction(); mainDb.execSQL("detach database ka_temp"); } Log.d(LOG_TAG, "finished juggling"); }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Delete the specified rowId in this tableId. Deletion respects sync * semantics. If the row is in the SyncState.new_row state, then the row and * its associated file attachments are immediately deleted. Otherwise, the row * is placed into the SyncState.deleted state and will be retained until the * device can delete the record on the server. * <p>//from w w w. ja va2 s.com * If you need to immediately delete a record that would otherwise sync to the * server, call updateRowETagAndSyncState(...) to set the row to * SyncState.new_row, and then call this method and it will be immediately * deleted (in this case, unless the record on the server was already deleted, * it will remain and not be deleted during any subsequent synchronizations). * * @param db * @param appName * @param tableId * @param rowId */ public void deleteDataInExistingDBTableWithId(SQLiteDatabase db, String appName, String tableId, String rowId) { SyncState syncState = getSyncState(db, appName, tableId, rowId); boolean dbWithinTransaction = db.inTransaction(); if (syncState == SyncState.new_row) { String[] whereArgs = { rowId }; String whereClause = DataTableColumns.ID + " = ?"; try { if (!dbWithinTransaction) { db.beginTransaction(); } db.delete(tableId, whereClause, whereArgs); if (!dbWithinTransaction) { db.setTransactionSuccessful(); } } finally { if (!dbWithinTransaction) { db.endTransaction(); } } File instanceFolder = new File(ODKFileUtils.getInstanceFolder(appName, tableId, rowId)); try { FileUtils.deleteDirectory(instanceFolder); } catch (IOException e) { // TODO Auto-generated catch block WebLogger.getLogger(appName).e(t, "Unable to delete this directory: " + instanceFolder.getAbsolutePath()); WebLogger.getLogger(appName).printStackTrace(e); } } else if (syncState == SyncState.synced || syncState == SyncState.changed) { String[] whereArgs = { rowId }; ContentValues values = new ContentValues(); values.put(DataTableColumns.SYNC_STATE, SyncState.deleted.name()); values.put(DataTableColumns.SAVEPOINT_TIMESTAMP, TableConstants.nanoSecondsFromMillis(System.currentTimeMillis())); try { if (!dbWithinTransaction) { db.beginTransaction(); } db.update(tableId, values, DataTableColumns.ID + " = ?", whereArgs); if (!dbWithinTransaction) { db.setTransactionSuccessful(); } } finally { if (!dbWithinTransaction) { db.endTransaction(); } } } }
From source file:info.staticfree.android.units.UnitUsageDBHelper.java
public void loadInitialUnitUsage() { final SQLiteDatabase db = getWritableDatabase(); // load the initial table in final ContentValues cv = new ContentValues(); Log.d(TAG, "init all weights hash"); final HashMap<String, Integer> allUnitWeights = new HashMap<String, Integer>(Unit.table.keySet().size()); Log.d(TAG, "adding all known weights..."); for (final String unitName : Unit.table.keySet()) { // don't add all uppercase names if (!unitName.toUpperCase().equals(unitName)) { allUnitWeights.put(unitName, 0); }//from w w w . j a v a 2s .co m } Log.d(TAG, "adding all known functions..."); for (final String functionName : BuiltInFunction.table.keySet()) { allUnitWeights.put(functionName + "(", 0); } // for (final String functionName: TabularFunction.table.keySet()){ // allUnitWeights.put(functionName + "(", 0); // } // for (final String functionName: ComputedFunction.table.keySet()){ // allUnitWeights.put(functionName + "(", 0); // } for (final String functionName : DefinedFunction.table.keySet()) { allUnitWeights.put(functionName + "(", 0); } Log.d(TAG, "adding common weights"); addAll(loadInitialWeights(R.raw.common_weights), allUnitWeights); Log.d(TAG, "adding regional weights"); addAll(loadInitialWeights(R.raw.regional_weights), allUnitWeights); // This is so that things of common weight end up in non-random order // without having to do an SQL order-by. final ArrayList<String> sortedUnits = new ArrayList<String>(allUnitWeights.keySet()); Log.d(TAG, "Sorting units..."); Collections.sort(sortedUnits); Log.d(TAG, "Adding all sorted units..."); final HashMap<String, String> fingerprints = loadFingerprints(); db.beginTransaction(); for (final String unitName : sortedUnits) { cv.put(UsageEntry._UNIT, unitName); cv.put(UsageEntry._USE_COUNT, allUnitWeights.get(unitName)); final String fpr = fingerprints.containsKey(unitName) ? fingerprints.get(unitName) : getFingerprint(unitName); fingerprints.put(unitName, fpr); cv.put(UsageEntry._FACTOR_FPRINT, fpr); db.insert(DB_USAGE_TABLE, null, cv); } db.setTransactionSuccessful(); db.endTransaction(); db.close(); context.getContentResolver().notifyChange(UsageEntry.CONTENT_URI, null); // If we have the right permissons, save the fingerprints file to a JSON file // which can then be imported into the app to speed up initial fingerpint loading. if (context.checkCallingOrSelfPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { final File externalStorage = Environment.getExternalStorageDirectory(); final File fprintsOutput = new File(externalStorage, "units_fingerprints.json"); final JSONObject jo = new JSONObject(fingerprints); try { final FileWriter fw = new FileWriter(fprintsOutput); fw.write(jo.toString(1)); fw.close(); Log.i(TAG, "fingerprints written to: " + fprintsOutput.getCanonicalPath()); } catch (final Exception e) { e.printStackTrace(); } } Log.d(TAG, "done!"); }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * If the tableId is not recorded in the TableDefinition metadata table, then * create the tableId with the indicated columns. This will synthesize * reasonable metadata KVS entries for table. * /*from w w w. j a v a2 s . co m*/ * If the tableId is present, then this is a no-op. * * @param db * @param appName * @param tableId * @param columns * @return the ArrayList<ColumnDefinition> of the user columns in the table. */ public ArrayList<ColumnDefinition> createOrOpenDBTableWithColumns(SQLiteDatabase db, String appName, String tableId, List<Column> columns) { boolean dbWithinTransaction = db.inTransaction(); boolean success = false; ArrayList<ColumnDefinition> orderedDefs = ColumnDefinition.buildColumnDefinitions(appName, tableId, columns); try { if (!dbWithinTransaction) { db.beginTransaction(); } if (!hasTableId(db, tableId)) { createDBTableWithColumns(db, appName, tableId, orderedDefs); } if (!dbWithinTransaction) { db.setTransactionSuccessful(); } success = true; return orderedDefs; } finally { if (!dbWithinTransaction) { db.endTransaction(); } if (success == false) { // Get the names of the columns StringBuilder colNames = new StringBuilder(); if (columns != null) { for (Column column : columns) { colNames.append(" ").append(column.getElementKey()).append(","); } if (colNames != null && colNames.length() > 0) { colNames.deleteCharAt(colNames.length() - 1); WebLogger.getLogger(appName).e(t, "createOrOpenDBTableWithColumns: Error while adding table " + tableId + " with columns:" + colNames.toString()); } } else { WebLogger.getLogger(appName).e(t, "createOrOpenDBTableWithColumns: Error while adding table " + tableId + " with columns: null"); } } } }
From source file:org.ttrssreader.controllers.DBHelper.java
/** * remove specified mark in the temporary mark table for specified * articles and then cleanup this table//from w w w . ja va2s . co m * * @param ids article IDs, which mark should be reseted * @param mark article mark to be reseted */ void setMarked(Map<Integer, String> ids, String mark) { if (!isDBAvailable()) return; SQLiteDatabase db = getOpenHelper().getWritableDatabase(); writeLock(true); db.beginTransaction(); try { ContentValues cv = new ContentValues(1); for (String idList : StringSupport.convertListToString(ids.keySet(), 1000)) { cv.putNull(mark); db.update(TABLE_MARK, cv, "id IN(" + idList + ")", null); db.delete(TABLE_MARK, "isUnread IS null AND isStarred IS null AND isPublished IS null", null); } // Insert notes afterwards and only if given note is not null cv = new ContentValues(1); for (Integer id : ids.keySet()) { String note = ids.get(id); if (note == null || note.equals("")) continue; cv.put(MARK_NOTE, note); db.update(TABLE_MARK, cv, "id=" + id, null); } db.setTransactionSuccessful(); } finally { db.endTransaction(); writeLock(false); } }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Change the conflictType for the given row from null (not in conflict) to * the specified one./* w w w .j av a 2 s . c o m*/ * * @param db * @param tableId * @param rowId * @param conflictType * expected to be one of ConflictType.LOCAL_DELETED_OLD_VALUES (0) or * ConflictType.LOCAL_UPDATED_UPDATED_VALUES (1) */ public void placeRowIntoConflict(SQLiteDatabase db, String tableId, String rowId, int conflictType) { String whereClause = String.format("%s = ? AND %s IS NULL", DataTableColumns.ID, DataTableColumns.CONFLICT_TYPE); String[] whereArgs = { rowId }; ContentValues cv = new ContentValues(); cv.put(DataTableColumns.SYNC_STATE, SyncState.in_conflict.name()); cv.put(DataTableColumns.CONFLICT_TYPE, conflictType); boolean dbWithinTransaction = db.inTransaction(); try { if (!dbWithinTransaction) { db.beginTransaction(); } db.update(tableId, cv, whereClause, whereArgs); if (!dbWithinTransaction) { db.setTransactionSuccessful(); } } finally { if (!dbWithinTransaction) { db.endTransaction(); } } }
From source file:net.smart_json_database.JSONDatabase.java
public int insert(JSONEntity entity) { int returnValue = -1; SQLiteDatabase db = dbHelper.getWritableDatabase(); try {//from w w w .java 2 s . c om db.beginTransaction(); ContentValues values = new ContentValues(); values.put("createDate", Util.DateToString(entity.getCreationDate())); values.put("updateDate", Util.DateToString(entity.getUpdateDate())); values.put("data", entity.getData().toString()); values.put("type", entity.getType()); int uid = Util.LongToInt(db.insert(TABLE_JSON_DATA, null, values)); returnValue = uid; //entity.setUid(uid); for (String name : entity.getTags().getToAdd()) { int tagid = -1; if (!tags.containsKey(name)) { tagid = insertTag(name, db); } else { tagid = tags.get(name); } if (relateTagWithJsonEntity(tagid, uid, db) == -1) { throw new Exception("could not relate entity with tags"); } } for (HasMany hasMany : entity.getHasManyRelations().values()) { // for(Integer id : hasMany.getToRemove()) // { // deleteRelation(hasMany.getName(), uid, id, db); // } for (Integer id : hasMany.getToAdd()) { insertRelation(hasMany.getName(), uid, id, db); } } for (BelongsTo belongsTo : entity.getBelongsToRelations().values()) { // for(Integer id : belongsTo.getToRemove()) // { // deleteRelation(belongsTo.getName(), id ,uid, db); // } for (Integer id : belongsTo.getToAdd()) { insertRelation(belongsTo.getName(), id, uid, db); } } db.setTransactionSuccessful(); notifyListenersOnEntityChange(returnValue, IDatabaseChangeListener.CHANGETYPE_INSERT); } catch (Exception e) { returnValue = -1; } finally { db.endTransaction(); db.close(); } return returnValue; }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Changes the conflictType for the given row from the specified one to null * and set the sync state of this row to the indicated value. In general, you * should first update the local conflict record with its new values, then * call deleteServerConflictRowWithId(...) and then call this method. * //ww w . ja va 2 s.c o m * @param db * @param tableId * @param rowId * @param syncState * @param conflictType */ public void restoreRowFromConflict(SQLiteDatabase db, String tableId, String rowId, SyncState syncState, int conflictType) { String whereClause = String.format("%s = ? AND %s = ?", DataTableColumns.ID, DataTableColumns.CONFLICT_TYPE); String[] whereArgs = { rowId, String.valueOf(conflictType) }; ContentValues cv = new ContentValues(); cv.putNull(DataTableColumns.CONFLICT_TYPE); cv.put(DataTableColumns.SYNC_STATE, syncState.name()); boolean dbWithinTransaction = db.inTransaction(); try { if (!dbWithinTransaction) { db.beginTransaction(); } db.update(tableId, cv, whereClause, whereArgs); if (!dbWithinTransaction) { db.setTransactionSuccessful(); } } finally { if (!dbWithinTransaction) { db.endTransaction(); } } }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Insert or update a single table-level metadata KVS entry. * //from w w w .j a v a 2 s. c om * @param db * @param entry */ public void replaceDBTableMetadata(SQLiteDatabase db, KeyValueStoreEntry entry) { ContentValues values = new ContentValues(); values.put(KeyValueStoreColumns.TABLE_ID, entry.tableId); values.put(KeyValueStoreColumns.PARTITION, entry.partition); values.put(KeyValueStoreColumns.ASPECT, entry.aspect); values.put(KeyValueStoreColumns.VALUE_TYPE, entry.type); values.put(KeyValueStoreColumns.VALUE, entry.value); values.put(KeyValueStoreColumns.KEY, entry.key); boolean dbWithinTransaction = db.inTransaction(); try { if (!dbWithinTransaction) { db.beginTransaction(); } db.replace(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, null, values); if (!dbWithinTransaction) { db.setTransactionSuccessful(); } } finally { if (!dbWithinTransaction) { db.endTransaction(); } } }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Update the timestamp of the last entirely-successful synchronization * attempt of this table./*w w w . j a v a 2 s . c o m*/ * * @param db * @param tableId */ public void updateDBTableLastSyncTime(SQLiteDatabase db, String tableId) { if (tableId == null || tableId.length() <= 0) { throw new IllegalArgumentException(t + ": application name and table name must be specified"); } ContentValues cvTableDef = new ContentValues(); cvTableDef.put(TableDefinitionsColumns.LAST_SYNC_TIME, TableConstants.nanoSecondsFromMillis(System.currentTimeMillis())); boolean dbWithinTransaction = db.inTransaction(); try { if (!dbWithinTransaction) { db.beginTransaction(); } db.update(DatabaseConstants.TABLE_DEFS_TABLE_NAME, cvTableDef, TableDefinitionsColumns.TABLE_ID + "=?", new String[] { tableId }); if (!dbWithinTransaction) { db.setTransactionSuccessful(); } } finally { if (!dbWithinTransaction) { db.endTransaction(); } } }