List of usage examples for android.database.sqlite SQLiteDatabase beginTransaction
public void beginTransaction()
From source file:org.getlantern.firetweet.util.content.DatabaseUpgradeHelper.java
public static void safeUpgrade(final SQLiteDatabase db, final String table, final String[] newColNames, final String[] newColTypes, final boolean dropDirectly, final boolean strictMode, final Map<String, String> colAliases, final OnConflict onConflict) { if (newColNames == null || newColTypes == null || newColNames.length != newColTypes.length) throw new IllegalArgumentException( "Invalid parameters for upgrading table " + table + ", length of columns and types not match."); // First, create the table if not exists. final NewColumn[] newCols = NewColumn.createNewColumns(newColNames, newColTypes); final String createQuery = createTable(true, table).columns(newCols).buildSQL(); db.execSQL(createQuery);/* w w w . java2s. c o m*/ // We need to get all data from old table. final String[] oldCols = getColumnNames(db, table); if (strictMode) { final String oldCreate = getCreateSQL(db, table); final Map<String, String> map = getTypeMapByCreateQuery(oldCreate); boolean differenct = false; for (final NewColumn newCol : newCols) { if (!newCol.getType().equalsIgnoreCase(map.get(newCol.getName()))) { differenct = true; } } if (!differenct) return; } else if (oldCols == null || FiretweetArrayUtils.contentMatch(newColNames, oldCols)) return; if (dropDirectly) { db.beginTransaction(); db.execSQL(dropTable(true, table).getSQL()); db.execSQL(createQuery); db.setTransactionSuccessful(); db.endTransaction(); return; } final String tempTable = String.format(Locale.US, "temp_%s_%d", table, System.currentTimeMillis()); db.beginTransaction(); db.execSQL(alterTable(table).renameTo(tempTable).buildSQL()); db.execSQL(createQuery); final String[] notNullCols = getNotNullColumns(newCols); final String insertQuery = createInsertDataQuery(table, tempTable, newColNames, oldCols, colAliases, notNullCols, onConflict); if (insertQuery != null) { db.execSQL(insertQuery); } db.execSQL(dropTable(true, tempTable).getSQL()); db.setTransactionSuccessful(); db.endTransaction(); }
From source file:ru.gkpromtech.exhibition.db.Table.java
public void insert(T item, int conflictAlgorithm) { SQLiteDatabase db = mSqlHelper.getWritableDatabase(); try {//from w w w . j a v a2 s. c o m db.beginTransaction(); db.insertWithOnConflict(mTableName, null, itemToRow(item), conflictAlgorithm); db.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); } finally { db.endTransaction(); db.close(); } }
From source file:ru.gkpromtech.exhibition.db.Table.java
public void insert(List<T> items, int conflictAlgorithm) { SQLiteDatabase db = mSqlHelper.getWritableDatabase(); try {//from w ww .j a v a2 s . c om db.beginTransaction(); for (T item : items) db.insertWithOnConflict(mTableName, null, itemToRow(item), conflictAlgorithm); db.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); } finally { db.endTransaction(); db.close(); } }
From source file:ru.gkpromtech.exhibition.db.Table.java
public void update(T item, int conflictAlgorithm) { SQLiteDatabase db = mSqlHelper.getWritableDatabase(); try {/*from www . j a v a2 s.c om*/ db.beginTransaction(); db.updateWithOnConflict(mTableName, itemToRow(item), "id = ?", new String[] { String.valueOf(item.id) }, conflictAlgorithm); db.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); } finally { db.endTransaction(); db.close(); } }
From source file:ru.gkpromtech.exhibition.db.Table.java
public void update(List<T> items, int conflictAlgorithm) { SQLiteDatabase db = mSqlHelper.getWritableDatabase(); try {// ww w . jav a2s. c o m db.beginTransaction(); for (T item : items) db.updateWithOnConflict(mTableName, itemToRow(item), "id = ?", new String[] { String.valueOf(item.id) }, conflictAlgorithm); db.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); } finally { db.endTransaction(); db.close(); } }
From source file:ru.gkpromtech.exhibition.db.Table.java
public void deleteById(List<Integer> ids) { if (ids.isEmpty()) return;// ww w. j a va 2s. c o m SQLiteDatabase db = mSqlHelper.getWritableDatabase(); try { db.beginTransaction(); String args[] = DbHelper.makeArguments(ids.toArray(new Integer[ids.size()])); String params = DbHelper.makePlaceholders(args.length); db.delete(mTableName, "id IN (" + params + ")", args); db.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); } finally { db.endTransaction(); db.close(); } }
From source file:org.opendatakit.common.android.provider.impl.InstanceProviderImpl.java
/** * This method removes the entry from the content provider, and also removes * any associated files. files: form.xml, [formmd5].formdef, formname * {directory}//from w ww . j ava 2 s.com */ @Override public int delete(Uri uri, String where, String[] whereArgs) { List<String> segments = uri.getPathSegments(); if (segments.size() < 2 || segments.size() > 3) { throw new SQLException("Unknown URI (too many segments!) " + uri); } String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); String tableId = segments.get(1); // _ID in UPLOADS_TABLE_NAME String instanceId = (segments.size() == 3 ? segments.get(2) : null); SQLiteDatabase db = null; List<IdStruct> idStructs = new ArrayList<IdStruct>(); try { db = DatabaseFactory.get().getDatabase(getContext(), appName); db.beginTransaction(); boolean success = false; try { success = ODKDatabaseUtils.get().hasTableId(db, tableId); } catch (Exception e) { e.printStackTrace(); throw new SQLException("Unknown URI (exception testing for tableId) " + uri); } if (!success) { throw new SQLException("Unknown URI (missing data table for tableId) " + uri); } String dbTableName = "\"" + tableId + "\""; if (segments.size() == 2) { where = "(" + where + ") AND (" + InstanceColumns.DATA_INSTANCE_ID + "=? )"; if (whereArgs != null) { String[] args = new String[whereArgs.length + 1]; for (int i = 0; i < whereArgs.length; ++i) { args[i] = whereArgs[i]; } args[whereArgs.length] = instanceId; whereArgs = args; } else { whereArgs = new String[] { instanceId }; } } Cursor del = null; try { del = this.query(uri, null, where, whereArgs, null); del.moveToPosition(-1); while (del.moveToNext()) { String iId = ODKDatabaseUtils.get().getIndexAsString(del, del.getColumnIndex(InstanceColumns._ID)); String iIdDataTable = ODKDatabaseUtils.get().getIndexAsString(del, del.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID)); idStructs.add(new IdStruct(iId, iIdDataTable)); String path = ODKFileUtils.getInstanceFolder(appName, tableId, iIdDataTable); File f = new File(path); if (f.exists()) { if (f.isDirectory()) { FileUtils.deleteDirectory(f); } else { f.delete(); } } } } catch (IOException e) { e.printStackTrace(); throw new IllegalArgumentException("Unable to delete instance directory: " + e.toString()); } finally { if (del != null) { del.close(); } } for (IdStruct idStruct : idStructs) { db.delete(DatabaseConstants.UPLOADS_TABLE_NAME, InstanceColumns.DATA_INSTANCE_ID + "=?", new String[] { idStruct.idUploadsTable }); db.delete(dbTableName, DATA_TABLE_ID_COLUMN + "=?", new String[] { idStruct.idDataTable }); } db.setTransactionSuccessful(); } finally { if (db != null) { db.endTransaction(); db.close(); } } getContext().getContentResolver().notifyChange(uri, null); return idStructs.size(); }
From source file:com.ericsender.android_nanodegree.popmovie.com.ericsender.android_nanodegree.popmovie.data.TestProvider.java
public void testBasicFavoriteQueries() { //first insert movies: Map<Long, ContentValues> listContentValues = TestUtilities.createSortedMovieValues(getContext(), "popular"); Map<Long, Long> locationRowIds = TestUtilities.insertMovieRow(mContext, listContentValues); // Insert random favorites SQLiteDatabase db = new MovieDbHelper(getContext()).getWritableDatabase(); Set<Long> insertedMoviedIds = new HashSet<>(); try {// w w w . j a v a2s .com db.beginTransaction(); while (insertedMoviedIds.isEmpty()) for (Map.Entry<Long, ContentValues> e : listContentValues.entrySet()) insertedMoviedIds.add(TestUtilities.generateRandomFavoritesAndInsert(db, e.getValue())); insertedMoviedIds.remove(null); db.setTransactionSuccessful(); } finally { db.endTransaction(); db.close(); } // Test the basic content provider query Cursor favCursor = mContext.getContentResolver().query(MovieContract.FavoriteEntry.CONTENT_URI, null, null, null, null); // Make sure we get the correct cursor out of the database TestUtilities.validateFavoritesCursor(favCursor, listContentValues, insertedMoviedIds); // Has the NotificationUri been set correctly? --- we can only test this easily against API // level 19 or greater because getNotificationUri was added in API level 19. if (Build.VERSION.SDK_INT >= 19) { assertEquals("Error: Favoriate Query did not properly set NotificationUri", favCursor.getNotificationUri(), MovieContract.FavoriteEntry.buildUri()); } }
From source file:net.zionsoft.obadiah.model.Bible.java
private boolean removeTranslation(String translationShortName) { SQLiteDatabase db = null; try {//from w w w . ja va 2s . co m db = mDatabaseHelper.openDatabase(); if (db == null) { Analytics.trackException("Failed to open database."); return false; } db.beginTransaction(); TranslationHelper.removeTranslation(db, translationShortName); db.setTransactionSuccessful(); return true; } finally { if (db != null) { if (db.inTransaction()) { db.endTransaction(); } mDatabaseHelper.closeDatabase(); } } }
From source file:net.zionsoft.obadiah.model.Bible.java
private void downloadTranslation(String url, String translationShortName, OnDownloadProgressListener onProgress) throws Exception { ZipInputStream zis = null;//from www . j a v a 2 s . co m SQLiteDatabase db = null; try { db = mDatabaseHelper.openDatabase(); if (db == null) { Analytics.trackException("Failed to open database."); throw new Exception("Failed to open database for writing"); } db.beginTransaction(); TranslationHelper.createTranslationTable(db, translationShortName); zis = new ZipInputStream(NetworkHelper.getStream(url)); final byte buffer[] = new byte[2048]; final ByteArrayOutputStream os = new ByteArrayOutputStream(); int downloaded = 0; int read; ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { os.reset(); while ((read = zis.read(buffer, 0, 2048)) != -1) os.write(buffer, 0, read); final byte[] bytes = os.toByteArray(); String fileName = entry.getName(); fileName = fileName.substring(0, fileName.length() - 5); // removes the trailing ".json" if (fileName.equals("books")) { TranslationHelper.saveBookNames(db, new JSONObject(new String(bytes, "UTF8"))); } else { final String[] parts = fileName.split("-"); final int bookIndex = Integer.parseInt(parts[0]); final int chapterIndex = Integer.parseInt(parts[1]); TranslationHelper.saveVerses(db, translationShortName, bookIndex, chapterIndex, new JSONObject(new String(bytes, "UTF8"))); } onProgress.onProgress(++downloaded / 12); } db.setTransactionSuccessful(); } finally { if (db != null) { if (db.inTransaction()) { db.endTransaction(); } mDatabaseHelper.closeDatabase(); } if (zis != null) { try { zis.close(); } catch (IOException e) { // we can't do much here } } } }