List of usage examples for android.database.sqlite SQLiteDatabase setTransactionSuccessful
public void setTransactionSuccessful()
From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java
@Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { List<String> segments = uri.getPathSegments(); if (segments.size() < 1 || segments.size() > 2) { throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri); }// w w w . j ava 2 s. c o m String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); WebLogger log = WebLogger.getLogger(appName); String uriFormId = ((segments.size() == 2) ? segments.get(1) : null); boolean isNumericId = StringUtils.isNumeric(uriFormId); // Modify the where clause to account for the presence of // a form id. Accept either: // (1) numeric _ID value // (2) string FORM_ID value. String whereId; String[] whereIdArgs; if (uriFormId == null) { whereId = where; whereIdArgs = whereArgs; } else { if (TextUtils.isEmpty(where)) { whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?"; whereIdArgs = new String[1]; whereIdArgs[0] = uriFormId; } else { whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")"; whereIdArgs = new String[whereArgs.length + 1]; whereIdArgs[0] = uriFormId; for (int i = 0; i < whereArgs.length; ++i) { whereIdArgs[i + 1] = whereArgs[i]; } } } /* * First, find out what records match this query, and if they refer to two * or more (formId,formVersion) tuples, then be sure to remove all * FORM_MEDIA_PATH references. Otherwise, if they are all for the same * tuple, and the update specifies a FORM_MEDIA_PATH, move all the * non-matching directories elsewhere. */ Integer idValue = null; String tableIdValue = null; String formIdValue = null; HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>(); boolean multiset = false; Cursor c = null; try { c = this.query(uri, null, whereId, whereIdArgs, null); if (c == null) { throw new SQLException( "FAILED Update of " + uri + " -- query for existing row did not return a cursor"); } if (c.getCount() >= 1) { FormIdVersion ref = null; c.moveToPosition(-1); while (c.moveToNext()) { idValue = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class, c.getColumnIndex(FormsColumns._ID)); tableIdValue = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.TABLE_ID)); formIdValue = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_ID)); String tableId = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.TABLE_ID)); String formId = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_ID)); String formVersion = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_VERSION)); FormIdVersion cur = new FormIdVersion(tableId, formId, formVersion); int appRelativeMediaPathIdx = c.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH); String mediaPath = ODKDatabaseUtils.get().getIndexAsString(c, appRelativeMediaPathIdx); if (mediaPath != null) { mediaDirs.put(ODKFileUtils.asAppFile(appName, mediaPath), (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS); } if (ref != null && !ref.equals(cur)) { multiset = true; break; } else { ref = cur; } } } } catch (Exception e) { log.w(t, "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString()); if (e instanceof SQLException) { throw (SQLException) e; } else { throw new SQLException( "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString()); } } finally { if (c != null) { c.close(); } } if (multiset) { // don't let users manually update media path // we are referring to two or more (formId,formVersion) tuples. if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) { values.remove(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH); } } else if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) { // we are not a multiset and we are setting the media path // try to move all the existing non-matching media paths to // somewhere else... File mediaPath = ODKFileUtils.asAppFile(appName, values.getAsString(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)); for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) { File altPath = entry.getKey(); if (!altPath.equals(mediaPath)) { try { moveDirectory(appName, entry.getValue(), altPath); } catch (IOException e) { e.printStackTrace(); log.e(t, "Attempt to move " + altPath.getAbsolutePath() + " failed: " + e.toString()); } } } // OK. we have moved the existing form definitions elsewhere. We can // proceed with update... } // ensure that all values are correct and ignore some user-supplied // values... patchUpValues(appName, values); // Make sure that the necessary fields are all set if (values.containsKey(FormsColumns.DATE) == true) { Date today = new Date(); String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(today); values.put(FormsColumns.DISPLAY_SUBTEXT, ts); } SQLiteDatabase db = null; int count; try { // OK Finally, now do the update... db = DatabaseFactory.get().getDatabase(getContext(), appName); db.beginTransaction(); count = db.update(DatabaseConstants.FORMS_TABLE_NAME, values, whereId, whereIdArgs); db.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); log.w(t, "Unable to perform update " + uri); return 0; } finally { if (db != null) { db.endTransaction(); db.close(); } } if (count == 1) { Uri formUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), formIdValue); getContext().getContentResolver().notifyChange(formUri, null); Uri idUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), Long.toString(idValue)); getContext().getContentResolver().notifyChange(idUri, null); } else { getContext().getContentResolver().notifyChange(uri, null); } return count; }
From source file:net.smart_json_database.JSONDatabase.java
/** * Deletes all content without the meta data * //w ww . j ava 2 s.c om * @return true if all delte operations are succesfull */ public boolean clearAllTables() { boolean returnValue = true; SQLiteDatabase db = dbHelper.getWritableDatabase(); try { db.beginTransaction(); //db.execSQL("DELETE FROM " + TABLE_Meta); db.execSQL("DELETE FROM " + TABLE_TAG); db.execSQL("DELETE FROM " + TABLE_JSON_DATA); db.execSQL("DELETE FROM " + TABLE_REL_TAG_JSON_DATA); db.setTransactionSuccessful(); } catch (Exception e) { returnValue = false; } finally { db.endTransaction(); db.close(); } return returnValue; }
From source file:com.dm.wallpaper.board.databases.Database.java
public void addWallpapers(@NonNull WallpaperJson wallpaper) { String query = "INSERT INTO " + TABLE_WALLPAPERS + " (" + KEY_NAME + "," + KEY_AUTHOR + "," + KEY_URL + "," + KEY_THUMB_URL + "," + KEY_CATEGORY + "," + KEY_ADDED_ON + ") VALUES (?,?,?,?,?,?);"; SQLiteDatabase db = this.getWritableDatabase(); SQLiteStatement statement = db.compileStatement(query); db.beginTransaction();/* ww w .j av a 2 s . c om*/ for (int i = 0; i < wallpaper.getWallpapers.size(); i++) { statement.clearBindings(); statement.bindString(1, wallpaper.getWallpapers.get(i).name); statement.bindString(2, wallpaper.getWallpapers.get(i).author); statement.bindString(3, wallpaper.getWallpapers.get(i).url); statement.bindString(4, wallpaper.getWallpapers.get(i).thumbUrl == null ? wallpaper.getWallpapers.get(i).url : wallpaper.getWallpapers.get(i).thumbUrl); statement.bindString(5, wallpaper.getWallpapers.get(i).category); statement.bindString(6, TimeHelper.getLongDateTime()); statement.execute(); } db.setTransactionSuccessful(); db.endTransaction(); db.close(); }
From source file:net.smart_json_database.JSONDatabase.java
public boolean deleteAll() { SQLiteDatabase db = dbHelper.getWritableDatabase(); boolean returnValue = false; try {/*from w w w .j a va2s . c o m*/ db.beginTransaction(); db.delete(TABLE_REL_JSON_DATA_JSON_DATA, "", null); db.delete(TABLE_REL_JSON_DATA_JSON_DATA, "", null); db.delete(TABLE_REL_TAG_JSON_DATA, "", null); db.delete(TABLE_JSON_DATA, "", null); db.setTransactionSuccessful(); returnValue = true; } catch (Exception e) { returnValue = false; } finally { db.endTransaction(); db.close(); } return returnValue; }
From source file:mobisocial.bento.anyshare.util.DBHelper.java
@Override public void onCreate(SQLiteDatabase db) { db.beginTransaction();/*from w w w .j av a2 s. c om*/ createTable(db, ItemObject.TABLE, null, ItemObject._ID, "INTEGER PRIMARY KEY", ItemObject.FEEDNAME, "TEXT", ItemObject.TITLE, "TEXT", ItemObject.DESC, "TEXT", ItemObject.TIMESTAMP, "INTEGER", ItemObject.RAW, "BLOB", ItemObject.OBJHASH, "INTEGER", ItemObject.PARENT_ID, "INTEGER"); createIndex(db, "INDEX", "objects_by_hash", ItemObject.TABLE, ItemObject.OBJHASH); createIndex(db, "INDEX", "objects_timestamp", ItemObject.TABLE, ItemObject.TIMESTAMP); db.execSQL("CREATE INDEX objects_by_parent_id ON " + ItemObject.TABLE + "(" + ItemObject.PARENT_ID + ", " + ItemObject.TIMESTAMP + ")"); db.setVersion(VERSION); db.setTransactionSuccessful(); db.endTransaction(); this.onOpen(db); //} }
From source file:org.devtcg.five.provider.FiveSyncAdapter.java
@Override public void getServerDiffs(SyncContext context, AbstractSyncProvider serverDiffs) { if (mSource != ((FiveProvider) serverDiffs).mSource) throw new IllegalStateException("What the hell happened here?"); context.moreRecordsToGet = true;/*from w w w . jav a 2s . com*/ /* Source must have been deleted or something? */ if (mSource.moveToFirst() == false) return; AuthHelper.setCredentials(sClient, mSource); long modifiedSince; SQLiteDatabase db = serverDiffs.getDatabase(); db.beginTransaction(); try { modifiedSince = getServerDiffsImpl(context, serverDiffs, FEED_ARTISTS); if (modifiedSince >= 0) getImageData(context, serverDiffs, FEED_ARTISTS, modifiedSince); modifiedSince = getServerDiffsImpl(context, serverDiffs, FEED_ALBUMS); if (modifiedSince >= 0) getImageData(context, serverDiffs, FEED_ALBUMS, modifiedSince); getServerDiffsImpl(context, serverDiffs, FEED_SONGS); getServerDiffsImpl(context, serverDiffs, FEED_PLAYLISTS); getServerDiffsImpl(context, serverDiffs, FEED_PLAYLIST_SONGS); db.setTransactionSuccessful(); } finally { db.endTransaction(); } /* This is a very naive implementation... */ if (context.hasCanceled() == false && context.hasError() == false) context.moreRecordsToGet = false; }
From source file:com.example.android.touroflondon.data.TourDbHelper.java
/** * Extract Route data from a {@link JSONArray} of save it in the database. * * @param data// w w w. j a v a 2 s. c om */ public void loadRoute(JSONArray data) throws JSONException { SQLiteDatabase db = this.getWritableDatabase(); // Empty the route table to remove all existing data db.delete(TourContract.RouteEntry.TABLE_NAME, null, null); // Need to complete transaction first to clear data db.close(); // Begin the insert transaction db = this.getWritableDatabase(); db.beginTransaction(); // Loop over each location in array for (int i = 0; i < data.length(); i++) { // extract data JSONObject poi = data.getJSONObject(i); final double lat = poi.getDouble("lat"); final double lng = poi.getDouble("lng"); // Construct insert statement ContentValues cv = new ContentValues(); cv.put(TourContract.RouteEntry.COLUMN_NAME_LAT, lat); cv.put(TourContract.RouteEntry.COLUMN_NAME_LNG, lng); // Insert data db.insert(TourContract.RouteEntry.TABLE_NAME, null, cv); } if (db != null) { // All insert statement have been submitted, mark transaction as successful db.setTransactionSuccessful(); db.endTransaction(); } }
From source file:com.example.google.touroflondon.data.TourDbHelper.java
/** * Extract Route data from a {@link JSONArray} of save it in the database. * // ww w .j av a2 s . c o m * @param data */ public void loadRoute(JSONArray data) throws JSONException { SQLiteDatabase db = this.getWritableDatabase(); // Empty the route table to remove all existing data db.delete(TourContract.RouteEntry.TABLE_NAME, null, null); // Need to complete transaction first to clear data db.close(); // Begin the insert transaction db = this.getWritableDatabase(); db.beginTransaction(); // Loop over each location in array for (int i = 0; i < data.length(); i++) { // extract data JSONObject poi = data.getJSONObject(i); final double lat = poi.getDouble("lat"); final double lng = poi.getDouble("lng"); // Construct insert statement ContentValues cv = new ContentValues(); cv.put(TourContract.RouteEntry.COLUMN_NAME_LAT, lat); cv.put(TourContract.RouteEntry.COLUMN_NAME_LNG, lng); // Insert data db.insert(TourContract.RouteEntry.TABLE_NAME, null, cv); } if (db != null) { // All insert statement have been submitted, mark transaction as // successful db.setTransactionSuccessful(); db.endTransaction(); } }
From source file:net.smart_json_database.JSONDatabase.java
public boolean delete(JSONEntity entity) { boolean returnValue = false; if (entity.getUid() == -1) { return returnValue; }// w ww .j a v a 2 s . co m SQLiteDatabase db = dbHelper.getWritableDatabase(); try { db.beginTransaction(); String[] params = new String[] { "" + entity.getUid() }; db.delete(TABLE_REL_JSON_DATA_JSON_DATA, "from_id = ?", params); db.delete(TABLE_REL_JSON_DATA_JSON_DATA, "to_id = ?", params); db.delete(TABLE_REL_TAG_JSON_DATA, "to_id = ?", params); db.delete(TABLE_JSON_DATA, "json_uid = ?", params); db.setTransactionSuccessful(); notifyListenersOnEntityChange(entity.getUid(), IDatabaseChangeListener.CHANGETYPE_DELETE); returnValue = true; } catch (Exception e) { returnValue = false; } finally { db.endTransaction(); db.close(); } return returnValue; }
From source file:ru.orangesoftware.financisto2.db.MyEntityManager.java
public long insertBudget(Budget budget) { SQLiteDatabase db = db(); db.beginTransaction();// w w w . j a v a 2 s. c o m try { if (budget.id > 0) { deleteBudget(budget.id); } long id = 0; Recur recur = RecurUtils.createFromExtraString(budget.recur); Period[] periods = RecurUtils.periods(recur); for (int i = 0; i < periods.length; i++) { Period p = periods[i]; budget.id = -1; budget.parentBudgetId = id; budget.recurNum = i; budget.startDate = p.start; budget.endDate = p.end; long bid = super.saveOrUpdate(budget); if (i == 0) { id = bid; } } db.setTransactionSuccessful(); return id; } finally { db.endTransaction(); } }