List of usage examples for android.content ContentValues valueSet
public Set<Map.Entry<String, Object>> valueSet()
From source file:net.openwatch.acluaz.fragment.FormFragment.java
/** * Populate form given the db_id of an Incident in the database * This currently assumes that the database columns are equal to the view_tags (json keys) * @param container//w w w. j av a 2 s .co m * @param db_id */ protected void fillFormFromDatabase(ViewGroup container, int db_id) { String TAG = "FormFragment-fillFormFromDatabase"; Incident incident = Incident.objects(this.getActivity().getApplicationContext()).get(db_id); if (incident == null) return; ContentValues values = new ContentValues(); try { incident.collectData(getActivity().getApplicationContext(), values, Incident.class); } catch (IllegalArgumentException e) { Log.e(TAG, "Unable to collect ContentValues from Incident"); e.printStackTrace(); } catch (IllegalAccessException e) { Log.e(TAG, "Unable to collect ContentValues from Incident"); e.printStackTrace(); } View form_input; for (Entry<String, ?> entry : values.valueSet()) { if (entry.getKey().compareTo(getString(R.string.device_lat)) == 0 || entry.getKey().compareTo(getString(R.string.device_lon)) == 0) { // Combine lat and lon into a Location and tag the gps toggle form_input = container.findViewById(R.id.gps_toggle); Location loc = new Location("db"); loc.setLatitude(values.getAsDouble(DBConstants.DEVICE_LAT)); loc.setLongitude(values.getAsDouble(DBConstants.DEVICE_LON)); form_input.setTag(R.id.view_tag, loc); } else if (entry.getKey().compareTo(getString(R.string.date_tag)) == 0) { form_input = container.findViewById(R.id.date_input); if (form_input == null || entry.getValue() == null) continue; String date = (String) entry.getValue(); try { ((EditText) form_input) .setText(Constants.date_formatter.format(Constants.datetime_formatter.parse(date))); form_input = container.findViewById(R.id.time_input); if (form_input == null) continue; ((EditText) form_input) .setText(Constants.time_formatter.format(Constants.datetime_formatter.parse(date))); } catch (ParseException e) { Log.e(TAG, "Error setting date time form fields from database datetime"); e.printStackTrace(); } } else { // If the column value is simply bound to the view // with tag equal to column name... form_input = container.findViewWithTag(entry.getKey()); setFormFieldValue(form_input, entry); } } }
From source file:com.ichi2.anki.provider.CardContentProvider.java
@Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { Timber.d("CardContentProvider.update"); Collection col = CollectionHelper.getInstance().getCol(getContext()); if (col == null) { return 0; }/*from w w w . jav a2s . com*/ // Find out what data the user is requesting int match = sUriMatcher.match(uri); int updated = 0; // Number of updated entries (return value) switch (match) { case NOTES: throw new IllegalArgumentException("Not possible to update notes directly (only through data URI)"); case NOTES_ID: { /* Direct access note details */ Note currentNote = getNoteFromUri(uri, col); // the key of the ContentValues contains the column name // the value of the ContentValues contains the row value. Set<Map.Entry<String, Object>> valueSet = values.valueSet(); for (Map.Entry<String, Object> entry : valueSet) { String key = entry.getKey(); if (key.equals(FlashCardsContract.Note.FLDS)) { // Update FLDS Timber.d("CardContentProvider: flds update..."); String newFldsEncoded = (String) entry.getValue(); String[] flds = Utils.splitFields(newFldsEncoded); // Check that correct number of flds specified if (flds.length != currentNote.getFields().length) { throw new IllegalArgumentException("Incorrect flds argument : " + newFldsEncoded); } // Update the note for (int idx = 0; idx < flds.length; idx++) { currentNote.setField(idx, flds[idx]); } updated++; } else if (key.equals(FlashCardsContract.Note.TAGS)) { // Update tags Timber.d("CardContentProvider: tags update..."); currentNote.setTagsFromStr((String) entry.getValue()); updated++; } else { // Unsupported column throw new IllegalArgumentException("Unsupported column: " + key); } } Timber.d("CardContentProvider: Saving note..."); currentNote.flush(); break; } case NOTES_ID_CARDS: // TODO: To be implemented throw new UnsupportedOperationException("Not yet implemented"); // break; case NOTES_ID_CARDS_ORD: { Card currentCard = getCardFromUri(uri, col); boolean isDeckUpdate = false; long did = -1; // the key of the ContentValues contains the column name // the value of the ContentValues contains the row value. Set<Map.Entry<String, Object>> valueSet = values.valueSet(); for (Map.Entry<String, Object> entry : valueSet) { // Only updates on deck id is supported String key = entry.getKey(); isDeckUpdate = key.equals(FlashCardsContract.Card.DECK_ID); did = values.getAsLong(key); } /* now update the card */ if ((isDeckUpdate) && (did >= 0)) { Timber.d("CardContentProvider: Moving card to other deck..."); col.getDecks().flush(); currentCard.setDid(did); currentCard.flush(); updated++; } else { // User tries an operation that is not (yet?) supported. throw new IllegalArgumentException("Currently only updates of decks are supported"); } break; } case MODELS: throw new IllegalArgumentException("Cannot update models in bulk"); case MODELS_ID: // Get the input parameters String newModelName = values.getAsString(FlashCardsContract.Model.NAME); String newCss = values.getAsString(FlashCardsContract.Model.CSS); String newDid = values.getAsString(FlashCardsContract.Model.DECK_ID); String newFieldList = values.getAsString(FlashCardsContract.Model.FIELD_NAMES); if (newFieldList != null) { // Changing the field names would require a full-sync throw new IllegalArgumentException("Field names cannot be changed via provider"); } // Get the original note JSON JSONObject model = col.getModels().get(getModelIdFromUri(uri, col)); try { // Update model name and/or css if (newModelName != null) { model.put("name", newModelName); updated++; } if (newCss != null) { model.put("css", newCss); updated++; } if (newDid != null) { model.put("did", newDid); updated++; } col.getModels().save(model); } catch (JSONException e) { Timber.e(e, "JSONException updating model"); } break; case MODELS_ID_TEMPLATES: throw new IllegalArgumentException("Cannot update templates in bulk"); case MODELS_ID_TEMPLATES_ID: Long mid = values.getAsLong(CardTemplate.MODEL_ID); Integer ord = values.getAsInteger(CardTemplate.ORD); String name = values.getAsString(CardTemplate.NAME); String qfmt = values.getAsString(CardTemplate.QUESTION_FORMAT); String afmt = values.getAsString(CardTemplate.ANSWER_FORMAT); String bqfmt = values.getAsString(CardTemplate.BROWSER_QUESTION_FORMAT); String bafmt = values.getAsString(CardTemplate.BROWSER_ANSWER_FORMAT); // Throw exception if read-only fields are included if (mid != null || ord != null) { throw new IllegalArgumentException("Can update mid or ord"); } // Update the model try { Integer templateOrd = Integer.parseInt(uri.getLastPathSegment()); JSONObject existingModel = col.getModels().get(getModelIdFromUri(uri, col)); JSONArray templates = existingModel.getJSONArray("tmpls"); JSONObject template = templates.getJSONObject(templateOrd); if (name != null) { template.put("name", name); updated++; } if (qfmt != null) { template.put("qfmt", qfmt); updated++; } if (afmt != null) { template.put("afmt", afmt); updated++; } if (bqfmt != null) { template.put("bqfmt", bqfmt); updated++; } if (bafmt != null) { template.put("bafmt", bafmt); updated++; } // Save the model templates.put(templateOrd, template); existingModel.put("tmpls", templates); col.getModels().save(existingModel, true); } catch (JSONException e) { throw new IllegalArgumentException("Model is malformed", e); } break; case SCHEDULE: { Set<Map.Entry<String, Object>> valueSet = values.valueSet(); int cardOrd = -1; long noteID = -1; int ease = -1; long timeTaken = -1; for (Map.Entry<String, Object> entry : valueSet) { String key = entry.getKey(); if (key.equals(FlashCardsContract.ReviewInfo.NOTE_ID)) { noteID = values.getAsLong(key); } else if (key.equals(FlashCardsContract.ReviewInfo.CARD_ORD)) { cardOrd = values.getAsInteger(key); } else if (key.equals(FlashCardsContract.ReviewInfo.EASE)) { ease = values.getAsInteger(key); } else if (key.equals(FlashCardsContract.ReviewInfo.TIME_TAKEN)) { timeTaken = values.getAsLong(key); } } if (cardOrd != -1 && noteID != -1) { Card cardToAnswer = getCard(noteID, cardOrd, col); if (cardToAnswer != null) { answerCard(col, col.getSched(), cardToAnswer, ease, timeTaken); updated++; } else { Timber.e( "Requested card with noteId %d and cardOrd %d was not found. Either the provided " + "noteId/cardOrd were wrong or the card has been deleted in the meantime.", noteID, cardOrd); } } break; } case DECKS: throw new IllegalArgumentException("Can't update decks in bulk"); case DECKS_ID: throw new UnsupportedOperationException("Not yet implemented"); case DECK_SELECTED: { Set<Map.Entry<String, Object>> valueSet = values.valueSet(); for (Map.Entry<String, Object> entry : valueSet) { String key = entry.getKey(); if (key.equals(FlashCardsContract.Deck.DECK_ID)) { long deckId = values.getAsLong(key); if (selectDeckWithCheck(col, deckId)) { updated++; } } } break; } default: // Unknown URI type throw new IllegalArgumentException("uri " + uri + " is not supported"); } return updated; }
From source file:io.requery.android.database.sqlite.SQLiteDatabase.java
/** * General method for inserting a row into the database. * * @param table the table to insert the row into * @param nullColumnHack optional; may be <code>null</code>. * SQL doesn't allow inserting a completely empty row without * naming at least one column name. If your provided <code>initialValues</code> is * empty, no column names are known and an empty row can't be inserted. * If not set to null, the <code>nullColumnHack</code> parameter * provides the name of nullable column name to explicitly insert a NULL into * in the case where your <code>initialValues</code> is empty. * @param initialValues this map contains the initial column values for the * row. The keys should be the column names and the values the * column values/*from w ww. j a v a2s . com*/ * @param conflictAlgorithm for insert conflict resolver * @return the row ID of the newly inserted row * OR the primary key of the existing row if the input param 'conflictAlgorithm' = * {@link #CONFLICT_IGNORE} * OR -1 if any error */ @SuppressWarnings("StringConcatenationInsideStringBufferAppend") public long insertWithOnConflict(String table, String nullColumnHack, ContentValues initialValues, @ConflictAlgorithm int conflictAlgorithm) { acquireReference(); try { StringBuilder sql = new StringBuilder(); sql.append("INSERT"); sql.append(CONFLICT_VALUES[conflictAlgorithm]); sql.append(" INTO "); sql.append(table); sql.append('('); Object[] bindArgs = null; int size = (initialValues != null && initialValues.size() > 0) ? initialValues.size() : 0; if (size > 0) { bindArgs = new Object[size]; int i = 0; for (Map.Entry<String, Object> entry : initialValues.valueSet()) { sql.append((i > 0) ? "," : ""); sql.append(entry.getKey()); bindArgs[i++] = entry.getValue(); } sql.append(')'); sql.append(" VALUES ("); for (i = 0; i < size; i++) { sql.append((i > 0) ? ",?" : "?"); } } else { sql.append(nullColumnHack + ") VALUES (NULL"); } sql.append(')'); SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs); try { return statement.executeInsert(); } finally { statement.close(); } } finally { releaseReference(); } }
From source file:io.requery.android.database.sqlite.SQLiteDatabase.java
/** * Convenience method for updating rows in the database. * * @param table the table to update in/* w ww. ja v a 2s . c o m*/ * @param values a map from column names to new column values. null is a * valid value that will be translated to NULL. * @param whereClause the optional WHERE clause to apply when updating. * Passing null will update all rows. * @param whereArgs You may include ?s in the where clause, which * will be replaced by the values from whereArgs. The values * will be bound as Strings. * @param conflictAlgorithm for update conflict resolver * @return the number of rows affected */ public int updateWithOnConflict(String table, ContentValues values, String whereClause, String[] whereArgs, @ConflictAlgorithm int conflictAlgorithm) { if (values == null || values.size() == 0) { throw new IllegalArgumentException("Empty values"); } acquireReference(); try { StringBuilder sql = new StringBuilder(120); sql.append("UPDATE "); sql.append(CONFLICT_VALUES[conflictAlgorithm]); sql.append(table); sql.append(" SET "); // move all bind args to one array int setValuesSize = values.size(); int bindArgsSize = (whereArgs == null) ? setValuesSize : (setValuesSize + whereArgs.length); Object[] bindArgs = new Object[bindArgsSize]; int i = 0; for (Map.Entry<String, Object> entry : values.valueSet()) { sql.append((i > 0) ? "," : ""); sql.append(entry.getKey()); bindArgs[i++] = entry.getValue(); sql.append("=?"); } if (whereArgs != null) { for (i = setValuesSize; i < bindArgsSize; i++) { bindArgs[i] = whereArgs[i - setValuesSize]; } } if (!TextUtils.isEmpty(whereClause)) { sql.append(" WHERE "); sql.append(whereClause); } SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs); try { return statement.executeUpdateDelete(); } finally { statement.close(); } } finally { releaseReference(); } }