List of usage examples for android.database.sqlite SQLiteDatabase update
public int update(String table, ContentValues values, String whereClause, String[] whereArgs)
From source file:com.example.blackberry.agoodandroidsample.SqlFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_sql, container, false); final CheckBox blueBox = (CheckBox) view.findViewById(R.id.checkBlue); final CheckBox brownBox = (CheckBox) view.findViewById(R.id.checkBrown); final CheckBox greenBox = (CheckBox) view.findViewById(R.id.checkGreen); final CheckBox orangeBox = (CheckBox) view.findViewById(R.id.checkOrange); final CheckBox pinkBox = (CheckBox) view.findViewById(R.id.checkPink); final CheckBox purpleBox = (CheckBox) view.findViewById(R.id.checkPurple); final CheckBox redBox = (CheckBox) view.findViewById(R.id.checkRed); final CheckBox yellowBox = (CheckBox) view.findViewById(R.id.checkYellow); final Button clearButton = (Button) view.findViewById(R.id.clearButton); clearButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { blueBox.setChecked(false);/*from ww w . j ava 2s . c o m*/ brownBox.setChecked(false); greenBox.setChecked(false); orangeBox.setChecked(false); pinkBox.setChecked(false); purpleBox.setChecked(false); redBox.setChecked(false); yellowBox.setChecked(false); } }); final Button saveButton = (Button) view.findViewById(R.id.saveButton); saveButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ColorDbHelper dbHelper = new ColorDbHelper(getContext()); SQLiteDatabase db = dbHelper.getWritableDatabase(); int size = Constants.COLORS_ALL.length; //Update the database for each color. for (int count = 0; count < size; count++) { switch (Constants.COLORS_ALL[count]) { case Constants.COLOR_BLUE: updateDb(db, Constants.COLOR_BLUE, blueBox.isChecked()); break; case Constants.COLOR_BROWN: updateDb(db, Constants.COLOR_BROWN, brownBox.isChecked()); break; case Constants.COLOR_GREEN: updateDb(db, Constants.COLOR_GREEN, greenBox.isChecked()); break; case Constants.COLOR_ORANGE: updateDb(db, Constants.COLOR_ORANGE, orangeBox.isChecked()); break; case Constants.COLOR_PINK: updateDb(db, Constants.COLOR_PINK, pinkBox.isChecked()); break; case Constants.COLOR_PURPLE: updateDb(db, Constants.COLOR_PURPLE, purpleBox.isChecked()); break; case Constants.COLOR_RED: updateDb(db, Constants.COLOR_RED, redBox.isChecked()); break; case Constants.COLOR_YELLOW: updateDb(db, Constants.COLOR_YELLOW, yellowBox.isChecked()); break; } } db.close(); } //Update the database with the user's chosen colors. private void updateDb(SQLiteDatabase db, int theColor, boolean checked) { ContentValues values = new ContentValues(); //Update the is favorite column based on the user's selection. if (checked) { values.put(ColorContract.ColorTable.COLUMN_NAME_ISFAVORITE, 1); } else { values.put(ColorContract.ColorTable.COLUMN_NAME_ISFAVORITE, 0); } //Update the row for the current color. String selection = ColorContract.ColorTable.COLUMN_NAME_COLOR_ID + " LIKE ?"; String[] selectionArgs = { String.valueOf(theColor) }; db.update(ColorContract.ColorTable.TABLE_NAME, values, selection, selectionArgs); } }); final Button loadButton = (Button) view.findViewById(R.id.loadButton); loadButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ColorDbHelper dbHelper = new ColorDbHelper(getContext()); SQLiteDatabase db = dbHelper.getWritableDatabase(); int size = Constants.COLORS_ALL.length; //Read the database for each color. for (int count = 0; count < size; count++) { switch (Constants.COLORS_ALL[count]) { case Constants.COLOR_BLUE: blueBox.setChecked(isFavourite(db, Constants.COLOR_BLUE)); break; case Constants.COLOR_BROWN: brownBox.setChecked(isFavourite(db, Constants.COLOR_BROWN)); break; case Constants.COLOR_GREEN: greenBox.setChecked(isFavourite(db, Constants.COLOR_GREEN)); break; case Constants.COLOR_ORANGE: orangeBox.setChecked(isFavourite(db, Constants.COLOR_ORANGE)); break; case Constants.COLOR_PINK: pinkBox.setChecked(isFavourite(db, Constants.COLOR_PINK)); break; case Constants.COLOR_PURPLE: purpleBox.setChecked(isFavourite(db, Constants.COLOR_PURPLE)); break; case Constants.COLOR_RED: redBox.setChecked(isFavourite(db, Constants.COLOR_RED)); break; case Constants.COLOR_YELLOW: yellowBox.setChecked(isFavourite(db, Constants.COLOR_YELLOW)); break; } } db.close(); } private boolean isFavourite(SQLiteDatabase db, int theColor) { //Define the columns we want returned. String[] projection = { ColorContract.ColorTable.COLUMN_NAME_COLOR_ID, ColorContract.ColorTable.COLUMN_NAME_ISFAVORITE }; //Define the columns for the where clause. String selection = ColorContract.ColorTable.COLUMN_NAME_COLOR_ID + " = " + theColor; Cursor cur = db.query(ColorContract.ColorTable.TABLE_NAME, projection, selection, null, null, null, null); cur.moveToFirst(); int fav = cur.getInt(1); cur.close(); if (fav == 0) { return false; } else { return true; } } }); return view; }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Update the timestamp of the last entirely-successful synchronization * attempt of this table.//from w ww. j a v a 2 s . co 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(); } } }
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 ww . j a v a 2 s . co 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:eu.inmite.apps.smsjizdenka.service.UpdateService.java
@Override protected void onHandleIntent(Intent intent) { if (intent == null) { return;//from ww w . j a v a2 s .c o m } final boolean force = intent.getBooleanExtra("force", false); try { Locale loc = Locale.getDefault(); String lang = loc.getISO3Language(); // http://www.loc.gov/standards/iso639-2/php/code_list.php; T-values if present both T and B if (lang == null || lang.length() == 0) { lang = ""; } int serverVersion = intent.getIntExtra("serverVersion", -1); boolean fromPush = serverVersion != -1; JSONObject versionJson = null; if (!fromPush) { versionJson = getVersion(true); serverVersion = versionJson.getInt("version"); } int localVersion = Preferences.getInt(c, Preferences.DATA_VERSION, -1); final String localLanguage = Preferences.getString(c, Preferences.DATA_LANGUAGE, ""); if (serverVersion <= localVersion && !force && lang.equals(localLanguage) && !LOCAL_DEFINITION_TESTING) { // don't update DebugLog.i("Nothing new, not updating"); return; } // update but don't notify about it. boolean firstLaunchNoUpdate = ((localVersion == -1 && getVersion(false).getInt("version") == serverVersion) || !lang.equals(localLanguage)); if (!firstLaunchNoUpdate) { DebugLog.i("There are new definitions available!"); } handleAuthorMessage(versionJson, lang, intent, fromPush); InputStream is = getIS(URL_TICKETS_ID); try { String json = readResult(is); JSONObject o = new JSONObject(json); JSONArray array = o.getJSONArray("tickets"); final SQLiteDatabase db = DatabaseHelper.get(this).getWritableDatabase(); for (int i = 0; i < array.length(); i++) { final JSONObject city = array.getJSONObject(i); try { final ContentValues cv = new ContentValues(); cv.put(Cities._ID, city.getInt("id")); cv.put(Cities.CITY, getStringLocValue(city, lang, "city")); if (city.has("city_pubtran")) { cv.put(Cities.CITY_PUBTRAN, city.getString("city_pubtran")); } cv.put(Cities.COUNTRY, city.getString("country")); cv.put(Cities.CURRENCY, city.getString("currency")); cv.put(Cities.DATE_FORMAT, city.getString("dateFormat")); cv.put(Cities.IDENTIFICATION, city.getString("identification")); cv.put(Cities.LAT, city.getDouble("lat")); cv.put(Cities.LON, city.getDouble("lon")); cv.put(Cities.NOTE, getStringLocValue(city, lang, "note")); cv.put(Cities.NUMBER, city.getString("number")); cv.put(Cities.P_DATE_FROM, city.getString("pDateFrom")); cv.put(Cities.P_DATE_TO, city.getString("pDateTo")); cv.put(Cities.P_HASH, city.getString("pHash")); cv.put(Cities.PRICE, city.getString("price")); cv.put(Cities.PRICE_NOTE, getStringLocValue(city, lang, "priceNote")); cv.put(Cities.REQUEST, city.getString("request")); cv.put(Cities.VALIDITY, city.getInt("validity")); if (city.has("confirmReq")) { cv.put(Cities.CONFIRM_REQ, city.getString("confirmReq")); } if (city.has("confirm")) { cv.put(Cities.CONFIRM, city.getString("confirm")); } final JSONArray additionalNumbers = city.getJSONArray("additionalNumbers"); for (int j = 0; j < additionalNumbers.length() && j < 3; j++) { cv.put("ADDITIONAL_NUMBER_" + (j + 1), additionalNumbers.getString(j)); } db.beginTransaction(); int count = db.update(DatabaseHelper.CITY_TABLE_NAME, cv, Cities._ID + " = " + cv.getAsInteger(Cities._ID), null); if (count == 0) { db.insert(DatabaseHelper.CITY_TABLE_NAME, null, cv); } db.setTransactionSuccessful(); getContentResolver().notifyChange(Cities.CONTENT_URI, null); } finally { if (db.inTransaction()) { db.endTransaction(); } } } Preferences.set(c, Preferences.DATA_VERSION, serverVersion); Preferences.set(c, Preferences.DATA_LANGUAGE, lang); if (!firstLaunchNoUpdate && !fromPush) { final int finalServerVersion = serverVersion; mHandler.post(new Runnable() { @Override public void run() { Toast.makeText(UpdateService.this, getString(R.string.cities_update_completed, finalServerVersion), Toast.LENGTH_LONG).show(); } }); } if (LOCAL_DEFINITION_TESTING) { DebugLog.w( "Local definition testing - data updated from assets - must be removed in production!"); } } finally { is.close(); } } catch (IOException e) { DebugLog.e("IOException when calling update: " + e.getMessage(), e); } catch (JSONException e) { DebugLog.e("JSONException when calling update: " + e.getMessage(), e); } }
From source file:org.frc836.database.DBSyncService.java
private void processMatches(JSONArray matches) { // TODO could be abstracted further try {//from w w w . jav a 2 s . com for (int i = 0; i < matches.length(); i++) { JSONObject row = matches.getJSONObject(i); Action action = Action.UPDATE; if (row.getInt(MatchStatsStruct.COLUMN_NAME_INVALID) != 0) { action = Action.DELETE; } ContentValues vals = MatchStatsStruct.getNewMatchStats().jsonToCV(row); // check if this entry exists already String[] projection = { MatchStatsStruct.COLUMN_NAME_ID, MatchStatsStruct.COLUMN_NAME_INVALID }; String[] where = { vals.getAsString(MatchStatsStruct.COLUMN_NAME_EVENT_ID), vals.getAsString(MatchStatsStruct.COLUMN_NAME_MATCH_ID), vals.getAsString(MatchStatsStruct.COLUMN_NAME_TEAM_ID), vals.getAsString(MatchStatsStruct.COLUMN_NAME_PRACTICE_MATCH) }; synchronized (ScoutingDBHelper.lock) { SQLiteDatabase db = ScoutingDBHelper.getInstance().getWritableDatabase(); Cursor c = db.query(MatchStatsStruct.TABLE_NAME, projection, // select MatchStatsStruct.COLUMN_NAME_EVENT_ID + "=? AND " + MatchStatsStruct.COLUMN_NAME_MATCH_ID + "=? AND " + MatchStatsStruct.COLUMN_NAME_TEAM_ID + "=? AND " + MatchStatsStruct.COLUMN_NAME_PRACTICE_MATCH + "=?", where, null, // don't // group null, // don't filter null, // don't order "0,1"); // limit to 1 try { int id = 0, invalid = 0; if (!c.moveToFirst()) { if (action == Action.UPDATE) action = Action.INSERT; else if (action == Action.DELETE) action = Action.NOTHING; } else { id = c.getInt(c.getColumnIndexOrThrow(MatchStatsStruct.COLUMN_NAME_ID)); invalid = c.getInt(c.getColumnIndexOrThrow(MatchStatsStruct.COLUMN_NAME_INVALID)); if (invalid > 0) // this field has not been sent to // server yet. action = Action.NOTHING; } String[] where2 = { String.valueOf(id) }; switch (action) { case UPDATE: db.update(MatchStatsStruct.TABLE_NAME, vals, MatchStatsStruct.COLUMN_NAME_ID + " = ?", where2); break; case INSERT: db.insert(MatchStatsStruct.TABLE_NAME, null, vals); break; case DELETE: db.delete(MatchStatsStruct.TABLE_NAME, MatchStatsStruct.COLUMN_NAME_ID + " = ?", where2); break; default: } } finally { if (c != null) c.close(); ScoutingDBHelper.getInstance().close(); } } } } catch (JSONException e) { // TODO handle error } }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Update the schema and data-modification ETags of a given tableId. * /* w w w .j ava 2 s .com*/ * @param db * @param tableId * @param schemaETag * @param lastDataETag */ public void updateDBTableETags(SQLiteDatabase db, String tableId, String schemaETag, String lastDataETag) { 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.SCHEMA_ETAG, schemaETag); cvTableDef.put(TableDefinitionsColumns.LAST_DATA_ETAG, lastDataETag); 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(); } } }
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. * /* w w w . j a v a2 s. c om*/ * @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.provider.impl.InstanceProviderImpl.java
@Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { List<String> segments = uri.getPathSegments(); if (segments.size() != 3) { throw new SQLException("Unknown URI (does not specify instance!) " + uri); }/*from www . j a v a 2 s. c om*/ String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); String tableId = segments.get(1); // _ID in UPLOADS_TABLE_NAME String instanceId = segments.get(2); SQLiteDatabase db = null; int count = 0; try { db = DatabaseFactory.get().getDatabase(getContext(), appName); 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 + "\""; // run the query to get all the ids... List<IdStruct> idStructs = new ArrayList<IdStruct>(); Cursor ref = null; try { // use this provider's query interface to get the set of ids that // match (if any) ref = this.query(uri, null, where, whereArgs, null); if (ref.getCount() != 0) { ref.moveToFirst(); do { String iId = ODKDatabaseUtils.get().getIndexAsString(ref, ref.getColumnIndex(InstanceColumns._ID)); String iIdDataTable = ODKDatabaseUtils.get().getIndexAsString(ref, ref.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID)); idStructs.add(new IdStruct(iId, iIdDataTable)); } while (ref.moveToNext()); } } finally { if (ref != null) { ref.close(); } } // update the values string... if (values.containsKey(InstanceColumns.XML_PUBLISH_STATUS)) { Date xmlPublishDate = new Date(); values.put(InstanceColumns.XML_PUBLISH_TIMESTAMP, TableConstants.nanoSecondsFromMillis(xmlPublishDate.getTime())); String xmlPublishStatus = values.getAsString(InstanceColumns.XML_PUBLISH_STATUS); if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) { String text = getDisplaySubtext(xmlPublishStatus, xmlPublishDate); values.put(InstanceColumns.DISPLAY_SUBTEXT, text); } } db.beginTransaction(); String[] args = new String[1]; for (IdStruct idStruct : idStructs) { args[0] = idStruct.idUploadsTable; count += db.update(DatabaseConstants.UPLOADS_TABLE_NAME, values, InstanceColumns._ID + "=?", args); } db.setTransactionSuccessful(); } finally { if (db != null) { db.endTransaction(); db.close(); } } getContext().getContentResolver().notifyChange(uri, null); return count; }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Update the ETag and SyncState of a given rowId. There should be exactly one * record for this rowId in thed database (i.e., no conflicts or checkpoints). * //from w ww . jav a 2s. c o m * @param db * @param tableId * @param rowId * @param rowETag * @param state */ public void updateRowETagAndSyncState(SQLiteDatabase db, String tableId, String rowId, String rowETag, SyncState state) { String whereClause = DataTableColumns.ID + " = ?"; String[] whereArgs = { rowId }; ContentValues cvDataTableVal = new ContentValues(); String sel = "SELECT * FROM " + tableId + " WHERE " + whereClause; String[] selArgs = whereArgs; Cursor cursor = rawQuery(db, sel, selArgs); // There must be only one row in the db if (cursor.getCount() != 1) { throw new IllegalArgumentException( t + ": row id " + rowId + " does not have exactly 1 row in table " + tableId); } cvDataTableVal.put(DataTableColumns.ROW_ETAG, rowETag); cvDataTableVal.put(DataTableColumns.SYNC_STATE, state.name()); boolean dbWithinTransaction = db.inTransaction(); try { if (!dbWithinTransaction) { db.beginTransaction(); } db.update(tableId, cvDataTableVal, whereClause, whereArgs); if (!dbWithinTransaction) { db.setTransactionSuccessful(); } } finally { if (!dbWithinTransaction) { db.endTransaction(); } } }
From source file:org.mitre.svmp.common.DatabaseHandler.java
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { switch (oldVersion) { case 1:/*from www . jav a 2s .com*/ // changed Connections table, recreate it recreateTable(TABLE_CONNECTIONS, db); case 2: addTableColumn(TABLE_CONNECTIONS, 6, "''", db); addTableColumn(TABLE_CONNECTIONS, 7, "0", db); case 3: // changed auth types, now the IDs begin with 1, not 0 db.execSQL("UPDATE Connections SET AuthType=1 WHERE AuthType=0;"); case 4: // added measurement info and performance data tables, no need to change existing info createTable(TABLE_MEASUREMENT_INFO, db); createTable(TABLE_PERFORMANCE_DATA, db); case 5: addTableColumn(TABLE_CONNECTIONS, 8, "''", db); // SessionToken column added case 6: addTableColumn(TABLE_CONNECTIONS, 9, "''", db); // CertificateAlias column added case 7: // changed encryption types, removed SSL/untrusted, now we just have SSL db.execSQL("UPDATE Connections SET EncryptionType=1 WHERE EncryptionType=2;"); case 8: // changed session handling, now the client is aware when a session token is not valid db.execSQL("UPDATE Connections SET SessionToken='';"); // clear out all existing session tokens addTableColumn(TABLE_CONNECTIONS, 10, "0", db); // SessionExpires column added addTableColumn(TABLE_CONNECTIONS, 11, "0", db); // SessionGracePeriod column added addTableColumn(TABLE_CONNECTIONS, 12, "0", db); // LastDisconnected column added case 9: // added Apps table, no need to change existing data createTable(TABLE_APPS, db); case 10: // we don't use the Connections table's SessionGracePeriod column anymore, but there's no way to drop it case 11: // we don't use the Connections table's LastDisconnected column anymore, but there's no way to drop it // added session info columns addTableColumn(TABLE_CONNECTIONS, 13, "''", db); // SessionHost column added addTableColumn(TABLE_CONNECTIONS, 14, "''", db); // SessionPort column added addTableColumn(TABLE_CONNECTIONS, 15, "''", db); // SessionWebrtc column added // clear any existing session info ContentValues values = new ContentValues(); values.put("SessionToken", ""); // attempt update try { db.update(Tables[TABLE_CONNECTIONS], values, null, null); } catch (Exception e) { e.printStackTrace(); } updateRecord(TABLE_CONNECTIONS, values, null); default: break; } }