@Override public Uri insert(Uri uri, ContentValues values) { /* * TODO: You need to implement this method. Note that values will have two columns (a key * column and a value column) and one row that contains the actual (key, value) pair to be * inserted. * * For actual storage, you can use any option. If you know how to use SQL, then you can use * SQLite. But this is not a requirement. You can use other storage options, such as the * internal storage option that we used in PA1. If you want to use that option, please * take a look at the code for PA1. */ /* Help taken from http://developer.android.com/guide/topics/providers/content-provider-creating.html & * http://developer.android.com/guide/topics/data/data-storage.html#filesInternal */ String key = (String) values.get("key"); String value = (String) values.get("value"); String filename = key; FileOutputStream outputStream; try { outputStream = getContext().openFileOutput(filename, Context.MODE_PRIVATE); outputStream.write(value.getBytes()); outputStream.close(); } catch (Exception e) { Log.e("insert", "File write failed"); } Log.v("insert", values.toString()); return uri; }
/** Reads the given property. Make sure this model has this property! */ public synchronized <TYPE> TYPE getValue(Property<TYPE> property) { Object value; if (setValues != null && setValues.containsKey(property.getColumnName())) { value = setValues.get(property.getColumnName()); } else if (values != null && values.containsKey(property.getColumnName())) { value = values.get(property.getColumnName()); } else if (getDefaultValues().containsKey(property.getColumnName())) { value = getDefaultValues().get(property.getColumnName()); } else { throw new UnsupportedOperationException( "Model Error: Did not read property " + property.name); // $NON-NLS-1$ } // resolve properties that were retrieved with a different type than accessed try { if (value instanceof String && property instanceof LongProperty) { return (TYPE) Long.valueOf((String) value); } else if (value instanceof String && property instanceof IntegerProperty) { return (TYPE) Integer.valueOf((String) value); } else if (value instanceof Integer && property instanceof LongProperty) { return (TYPE) Long.valueOf(((Number) value).longValue()); } return (TYPE) value; } catch (NumberFormatException e) { return (TYPE) getDefaultValues().get(property.name); } }
private String getInsertSQL(ContentValues next) { return "INSERT INTO devices (" + Devices.NAME + ", " + Devices.LOCATION + ", " + Devices.DEVICE_TYPE + ", " + Devices.POWER + ", " + Devices.REST_ID + ", " + Devices.CREATED_AT + ", " + Devices.UPDATED_AT + ") " + "values ('" + next.getAsString(Devices.NAME) + "', '" + next.getAsString(Devices.LOCATION) + "', '" + next.getAsString(Devices.DEVICE_TYPE) + "', '" + next.getAsBoolean(Devices.POWER) + "', '" + next.getAsInteger(Devices.REST_ID) + "', '" + next.get(Devices.CREATED_AT) + "', '" + next.get(Devices.UPDATED_AT) + "'" + ")"; }
/** * @return true if setValues or values contains this property, and the value stored is not null */ public boolean containsNonNullValue(Property<?> property) { if (setValues != null && setValues.containsKey(property.getColumnName())) { return setValues.get(property.getColumnName()) != null; } if (values != null && values.containsKey(property.getColumnName())) { return values.get(property.getColumnName()) != null; } return false; }
public void testSerialization() throws Exception { testTime(); subject.setUniqueID(Integer.MAX_VALUE); ContentValues serialized = subject.toStorage(); assertTrue(serialized.containsKey(DBAssistant.HIKE_START)); assertTrue(serialized.containsKey(DBAssistant.HIKE_END)); assertEquals(serialized.get(DBAssistant.HIKE_START), startTime); assertEquals(serialized.get(DBAssistant.HIKE_END), endTime); }
@SmallTest public void testGetValuesReturnsCorrectValues() { // Given UUID id = randomUUID(); String name = "Food"; Tag tag = new Tag(id, name); // When ContentValues values = mapper.getValues(tag); // Then assertNotNull(values); assertEquals(id.toString(), values.get(ID)); assertEquals(name, values.get(NAME)); }
private void createThumbnail(ContentValues map) throws IOException { File videoFile = fileFromResourceMap(map); Log.d("Creating thumbnail from video file " + videoFile.toString()); Bitmap bitmap = ThumbnailUtils.createVideoThumbnail( videoFile.toString(), MediaStore.Video.Thumbnails.MINI_KIND); if (bitmap == null) { Log.w("Error creating thumbnail"); return; } String filename = (String) map.get(Resources.FILENAME); if (TextUtils.isEmpty(filename)) { throw new IOException("Must specify FILENAME when inserting Resource"); } Uri thumbnailUri = Resources.buildThumbnailUri(filename + THUMBNAIL_EXT); OutputStream ostream; try { ostream = getContext().getContentResolver().openOutputStream(thumbnailUri); } catch (FileNotFoundException e) { Log.d("Could not open output stream for thumbnail storage: " + e.getLocalizedMessage()); return; } bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream); ostream.flush(); IOUtilities.closeStream(ostream); map.put(Resources.THUMBNAIL, thumbnailUri.toString()); }
@Override public Uri insert(Uri uri, ContentValues values) { if (sUriMatcher.match(uri) != INCOMING_CONTACT_COLLECTION_URI_INDICATOR) { throw new IllegalArgumentException("Unknow URI " + uri); } Log.d(TAG, "Enter insert"); if (!values.containsKey(ContactTableMetaData.CONTACT_ACCOUNT)) { throw new IllegalArgumentException("Failed to insert row, account is needed " + uri); } if (!values.containsKey(ContactTableMetaData.CONTACT_NICKNAME)) { values.put( ContactTableMetaData.CONTACT_NICKNAME, (String) values.get(ContactTableMetaData.CONTACT_ACCOUNT)); } SQLiteDatabase db = mOpenHelper.getWritableDatabase(); long rowId = db.insert(ContactTableMetaData.TABLE_NAME, ContactTableMetaData.CONTACT_ACCOUNT, values); if (rowId > 0) { Uri insertContactUri = ContentUris.withAppendedId(ContactTableMetaData.CONTENT_URI, rowId); getContext().getContentResolver().notifyChange(insertContactUri, null); Log.d(TAG, "insert uri=% " + insertContactUri.toString()); return insertContactUri; } throw new SQLiteException("Failed to insert row int " + uri); }
private void setConfirmation(int result) { if (result == DialogInterface.BUTTON_POSITIVE) { ApparelDBHelper mDbHelper = new ApparelDBHelper(context); SQLiteDatabase db = mDbHelper.getWritableDatabase(); String selection = ApparelTable.COLUMN_NAME_APPAREL_NAME + " = " + "'" + values.get(ApparelDB.ApparelTable.COLUMN_NAME_APPAREL_NAME) + "'" + " AND " + ApparelTable.COLUMN_NAME_APPAREL_TYPE + " = " + "'" + values.get(ApparelDB.ApparelTable.COLUMN_NAME_APPAREL_TYPE) + "'"; String[] selectionArgs = {}; long RowId = 0; switch (action) { case 1: Log.d("LOG", "In ApparelUpdate"); RowId = db.update(ApparelDB.ApparelTable.TABLE_NAME, values, selection, null); if (RowId == 0) { Log.d("LOG", "In ApparelWrite"); Log.d("value =", values.toString()); RowId = db.insert(ApparelDB.ApparelTable.TABLE_NAME, null, values); Log.d("LOG write id", String.valueOf(RowId)); } break; case 2: Log.d("LOG", "In ApparelDelete"); RowId = db.delete(ApparelDB.ApparelTable.TABLE_NAME, selection, null); break; } // db.close(); // Toast.makeText(context, "Apparel Data Added-Success"+String.valueOf(RowId), // Toast.LENGTH_LONG).show(); } }
@Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db = _dbAdapter.getWritableDatabase(); if (!(uriMatcher.match(uri) == PODCASTS)) throw new IllegalArgumentException("Illegal URI for insert"); if (values.get(COLUMN_MEDIA_URL) == null) throw new IllegalArgumentException("mediaUrl is required field for podcast"); Cursor mediaUrlCursor = db.rawQuery( "SELECT _id FROM podcasts WHERE mediaUrl = ?", new String[] {values.getAsString(COLUMN_MEDIA_URL)}); Long podcastId = null; if (mediaUrlCursor.moveToNext()) podcastId = mediaUrlCursor.getLong(0); mediaUrlCursor.close(); if (podcastId != null) { if (values.containsKey(COLUMN_MEDIA_URL) && values.containsKey(COLUMN_FILE_SIZE)) { String file = PodcastCursor.getStoragePath(getContext()) + String.valueOf(podcastId) + "." + PodcastCursor.getExtension(values.getAsString(COLUMN_MEDIA_URL)); // possible bug: file size shrinks for some reason -- don't use new one if (new File(file).length() > values.getAsInteger(COLUMN_FILE_SIZE)) values.remove(COLUMN_FILE_SIZE); } db.update("podcasts", values, COLUMN_ID + " = ?", new String[] {String.valueOf(podcastId)}); } else { podcastId = db.insert("podcasts", null, values); // find out if we should download new podcasts Cursor queueNewCursor = db.query( "subscriptions", new String[] {SubscriptionProvider.COLUMN_QUEUE_NEW}, "_id = ?", new String[] {String.valueOf(values.getAsLong(COLUMN_SUBSCRIPTION_ID))}, null, null, null); queueNewCursor.moveToFirst(); boolean queueNew = queueNewCursor.getInt(0) != 0; queueNewCursor.close(); // if the new podcast is less than 5 days old , and add it to the queue if (queueNew && values.containsKey(COLUMN_PUB_DATE)) { Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, -5); if (new Date(values.getAsLong(COLUMN_PUB_DATE) * 1000L).after(c.getTime())) { updateQueuePosition(podcastId, Integer.MAX_VALUE); } } } getContext().getContentResolver().notifyChange(uri, null); return PodcastProvider.getContentUri(podcastId); }
private void checkResults(Node<?> node, ExamplesTable table) { for (int i = 0; i < node.getCount(); i++) { for (Entry<String, String> en : table.getRows().get(i).entrySet()) { ContentValues values = node.getNode(i).getContentValue(); assertEquals(values.get(en.getKey()).toString(), en.getValue()); } } }
private static void adjustDateForIcs(ContentValues values) { if (atLeastIceCreamSandwich()) { if ("1".equals(values.get("allDay"))) { values.put("eventTimezone", Time.TIMEZONE_UTC); } else { values.put("eventTimezone", TimeZone.getDefault().getID()); } } }
private File fileFromResourceMap(ContentValues map) throws IOException { String videoDir = (String) map.get(Resources.DIRECTORY); if (TextUtils.isEmpty(videoDir)) { throw new IOException("Must specify DIRECTORY when inserting Resource"); } String filename = (String) map.get(Resources.FILENAME); if (TextUtils.isEmpty(filename)) { throw new IOException("Must specify FILENAME when inserting Resource"); } // Deprecated if (VizContract.PATH_VIDEO_UNLOCKED.equals(videoDir)) { return VizUtils.getPublicVideoFile(filename); } else if (VizContract.PATH_VIDEO_LOCKED.equals(videoDir)) { return VizUtils.getPrivateVideoFile(filename); } else { // All new files will have a literal path return new File(videoDir, filename); } }
@Override public Uri insert(Uri uri, ContentValues values) { //// Log.v(TAG,"Insert method called"); String key = (String) values.get(CommonConstants.KEY_FIELD); String value = (String) values.get(CommonConstants.VALUE_FIELD); int index = findSuccesssorIndex(key); String coordinator = dynamoNodes.get(index).getPortNum(); int num_nodes = dynamoNodes.size(); int sent_cnt = 0; while (sent_cnt != NUM_REPLICAS) { Node node = dynamoNodes.get(index); String portNum = node.getPortNum(); String modifiedKey = coordinator + CommonConstants.DOLLAR_SEP + portNum + CommonConstants.DOLLAR_SEP + key; //// Log.v(TAG,"Modified key "+modifiedKey); if (node.getPortNum().equals(localPort)) { // Log.v(TAG,"Inserting " + key + " in local "); insertLocalKeyValue(modifiedKey, value); } else { //// Log.v(TAG,"Sending " + key + " to "+ node.getPortNum()); StringBuilder sb = new StringBuilder(); sb.append(CommonConstants.MSG_TYPE_INSERT) .append(CommonConstants.HASH_SEP) .append(localPort) .append(CommonConstants.HASH_SEP) .append(modifiedKey) .append(CommonConstants.HASH_SEP) .append(value); String message = sb.toString(); try { String rcvdMessage = sendMessage(message, node.getPortNum()); //// Log.v(TAG,"Received "+rcvdMessage+" from "+node.getPortNum()); } catch (Exception e) { // Log.v(TAG,"Provider insert:: Failed port "+node.getPortNum()); } } index = (index + 1) % num_nodes; sent_cnt++; } return null; }
/** * Adds a new ingredient to MyBarTable. * * @param ingredientID _id column of the ingredient. * @param location "Home", "Work". * @return 0 if successful. */ public static int addMyBar(int ingredientID, String location) { ContentValues values = new ContentValues(); values.put("ingredientid", ingredientID); values.put("location", location); MyBarApplication.contentResolver().insert(MyBarContentProvider.CONTENTURI_MYBAR, values); // Print the added drink. Log.d( Data.class.getClass().getName(), "Added ID to " + "MyBarTable: " + values.get("ingredientid")); return 0; }
/** * Remove column from values, and throw a SecurityException if the value isn't within the * specified allowedValues. */ private void enforceAllowedValues(ContentValues values, String column, Object... allowedValues) { Object value = values.get(column); values.remove(column); for (Object allowedValue : allowedValues) { if (value == null && allowedValue == null) { return; } if (value != null && value.equals(allowedValue)) { return; } } throw new SecurityException("Invalid value for " + column + ": " + value); }
@Override public Uri insert(Uri uri, ContentValues values) { String newItemName = (String) values.get(Columns.ITEM); String creationDate = (String) values.get(Columns.CREATION_DATE); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("newitem", newItemName)); nameValuePairs.add(new BasicNameValuePair("creationdate", creationDate)); String result = httpRequest("http://" + ipAddress + "/postitlist_insert.php", nameValuePairs); Log.i( PostitListWidgetProvider.TAG, "PostitListDataProvider: requested to add new item: " + newItemName + "with creation date: " + creationDate + ", result is " + result); return null; }
private void load(Long id) { ContentValues content = db.get(id); String aux; // date aux = (String) content.get("date"); DatePicker dp = (DatePicker) findViewById(R.id.date); int year = Integer.parseInt(aux.substring(0, 4)); // datepicke month starts with 0 int month = Integer.parseInt(aux.substring(5, 7)) - 1; int day = Integer.parseInt(aux.substring(8, 10)); dp.updateDate(year, month, day); // km EditText auxText = (EditText) findViewById(R.id.km); aux = (String) content.get("odometer"); auxText.setText(aux); // liters auxText = (EditText) findViewById(R.id.liters); aux = (String) content.get("liters"); auxText.setText(aux); Log.d("TAG", "liters = " + aux); // type aux = (String) content.get("fuel"); RadioGroup aux2 = (RadioGroup) findViewById(R.id.type); for (int i = 0; i < aux2.getChildCount(); i++) { RadioButton aux3 = (RadioButton) aux2.getChildAt(i); Log.d("TAG", ">>" + aux3.getText().toString() + "==" + aux); if (aux3.getText().toString().equals(aux)) { Log.d("TAG", ">> Y << " + Integer.toString(i)); aux2.check(aux3.getId()); break; } } }
private void informMediaScanner(ContentValues map) throws IOException { final File videoFile = fileFromResourceMap(map); String dir = (String) map.get(Resources.DIRECTORY); if (VizUtils.isPublicDir(dir)) { Thread t = new Thread("AddVideoToGallery") { @Override public void run() { VizUtils.informMediaScanner(videoFile.toString()); } }; Utils.threadStart(t, "Failed to add video to gallery"); } }
private MatrixCursor getMatrixCursor(String id, String[] projection, ContentValues values) { Cursor c = get(id); if (c != null) { // Make a new MatrixCursor with the requested columns MatrixCursor mc = new MatrixCursorWithCachedColumns(projection, 1); if (c.getCount() == 0) { return mc; } Object[] row = new Object[projection.length]; if (values != null) { // Make a copy; we don't want to change the original values = new ContentValues(values); } int i = 0; for (String column : projection) { int columnIndex = c.getColumnIndex(column); if (columnIndex < 0) { mStats.mProjectionMissCount++; return null; } else { String value; if (values != null && values.containsKey(column)) { Object val = values.get(column); if (val instanceof Boolean) { value = (val == Boolean.TRUE) ? "1" : "0"; } else { value = values.getAsString(column); } values.remove(column); } else { value = c.getString(columnIndex); } row[i++] = value; } } if (values != null && values.size() != 0) { return null; } mc.addRow(row); mStats.mHitCount++; return mc; } mStats.mMissCount++; return null; }
public static void copyLongValue( ContentValues toValues, String toKey, ContentValues fromValues, String fromKey) { if (fromValues.containsKey(fromKey)) { long longValue; Object value = fromValues.get(fromKey); if (value instanceof Boolean) { if ((Boolean) value) { longValue = 1; } else { longValue = 0; } } else if (value instanceof String) { longValue = Long.parseLong((String) value); } else { longValue = ((Number) value).longValue(); } toValues.put(toKey, longValue); } }
public boolean CursorMatches(Cursor c, ContentValues cv) { for (int i = 0; i < c.getColumnCount(); i++) { String column = c.getColumnName(i); if (cv.containsKey(column)) { mAsserter.info("Comparing", "Column values for: " + column); Object value = cv.get(column); if (value == null) { if (!c.isNull(i)) { return false; } } else { if (c.isNull(i) || !value.toString().equals(c.getString(i))) { return false; } } } } return true; }
private boolean CursorMatches(Cursor c, String[] columns, ContentValues cv) { for (int i = 0; i < columns.length; i++) { String column = columns[i]; if (cv.containsKey(column)) { mAsserter.info("Comparing", "Column values for: " + column); Object value = cv.get(column); if (value == null) { if (!c.isNull(i)) { return false; } } else { if (c.isNull(i) || !value.toString().equals(c.getString(i))) { return false; } } } } return true; }
@Override public Uri insert(Uri uri, ContentValues values) { int uriType = osmURIMatcher.match(uri); long recordId = 0; switch (uriType) { case SETTINGS_METHOD: recordId = database.insert(TABLE, null, values); break; default: throw new IllegalArgumentException("Unknown URI: " + uri); } // notify getContext().getContentResolver().notifyChange(uri, null); if (recordId == -1) return Uri.parse(SETTINGS_PATH + "/" + NOEXIST); return Uri.parse(SETTINGS_PATH + "/" + values.get(KEY)); }
private String getContent(ListAdapter adapter) { StringBuilder builder = new StringBuilder(); char separator = ','; StockHistoryRepository historyRepository = new StockHistoryRepository(mContext.getApplicationContext()); int itemCount = adapter.getCount(); for (int i = 0; i < itemCount; i++) { Cursor cursor = (Cursor) adapter.getItem(i); // symbol. String symbol = cursor.getString(cursor.getColumnIndex(StockRepository.SYMBOL)); // use the latest price date here. String date; ContentValues latestPrice = historyRepository.getLatestPriceFor(symbol); if (latestPrice == null) continue; if (latestPrice.containsKey(StockHistory.DATE)) { date = (String) latestPrice.get(StockHistory.DATE); } else { date = getTodayAsString(); } // format date String csvDate = getDateInCsvFormat(date); // price. String price = cursor.getString(cursor.getColumnIndex(StockRepository.CURRENTPRICE)); // code builder.append(symbol); builder.append(separator); // price builder.append(price); builder.append(separator); // date builder.append(csvDate); builder.append(System.lineSeparator()); } return builder.toString(); }
/** * Insert a group * * @param values The values of the row * @return The URI for the new insertion */ public Uri groupInsert(ContentValues values) { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); long rowID = -1; // Insert the row try { // Make sure the ID is unique Object value = values.get(Group.Columns._ID); if (value != null) { int id = (Integer) value; if (id > -1) { final Cursor cursor = db.query( "groups", new String[] {Group.Columns._ID}, "_id = ?", new String[] {Integer.toString(id)}, null, null, null); if (cursor.moveToFirst()) { // It exists! Remove the ID so SQLite fills in a new one values.putNull(Group.Columns._ID); } } } // Perform the insertion rowID = db.insert("groups", Task.Columns.NAME, values); db.setTransactionSuccessful(); } finally { db.endTransaction(); } // Insertion failure if (rowID < 0) throw new SQLException("Failed to insert row"); Log.v(TAG, "Added new group with ID " + rowID); return ContentUris.withAppendedId(Task.Columns.CONTENT_URI, rowID); }
long fixAlarmInsert(ContentValues values) { // Why are we doing this? Is this not a programming bug if we try to // insert an already used id? SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); long rowId = -1; try { // Check if we are trying to re-use an existing id. Object value = values.get(ClockContract.AlarmsColumns._ID); if (value != null) { long id = (Long) value; if (id > -1) { final Cursor cursor = db.query( ALARMS_TABLE_NAME, new String[] {ClockContract.AlarmsColumns._ID}, ClockContract.AlarmsColumns._ID + " = ?", new String[] {id + ""}, null, null, null); if (cursor.moveToFirst()) { // Record exists. Remove the id so sqlite can generate a new one. values.putNull(ClockContract.AlarmsColumns._ID); } } } rowId = db.insert(ALARMS_TABLE_NAME, ClockContract.AlarmsColumns.RINGTONE, values); db.setTransactionSuccessful(); } finally { db.endTransaction(); } if (rowId < 0) { throw new SQLException("Failed to insert row"); } Log.v(LOG_TAG, "Added alarm rowId = " + rowId); return rowId; }
/** * This method overrides from DataAccesObject. A implementation of that method is given here. It * insert/update the ArrayList of AnimalKind objects into local Database */ @Override public void insert(ArrayList<DatabaseData> dataSet) { for (DatabaseData dataRow : dataSet) { AnimalKind animalKind = (AnimalKind) dataRow; ContentValues values = new ContentValues(); values.put(AnimalKindTable.COLUMN_KINDID, animalKind.getKindID()); values.put(AnimalKindTable.COLUMN_KINDNAME, animalKind.getKindName()); Cursor getID = database.rawQuery( "SELECT properID from Properties where properID = ?", new String[] {values.get(AnimalKindTable.COLUMN_KINDID).toString()}); if (getID == null) database.insert(AnimalKindTable.TABLE_ANIMALKIND, null, values); else database.replace(AnimalKindTable.TABLE_ANIMALKIND, null, values); getID.close(); } }
public void update(T entity) { Log.d("BaseDAO", "update by " + this.idColumn); SQLiteDatabase db = null; try { db = this.dbHelper.getWritableDatabase(); ContentValues cv = new ContentValues(); setContentValues(entity, cv, "update"); String where = this.idColumn + " = ?"; int id = Integer.parseInt(cv.get(this.idColumn).toString()); cv.remove(this.idColumn); Log.d("BaseDAO", "id:" + id); Log.d("BaseDAO", "where:" + where); String[] whereValue = {Integer.toString(id)}; db.update(this.tableName, cv, where, whereValue); } catch (Exception e) { Log.d("BaseDAO", "update DB Exception."); } finally { if (db != null) db.close(); } }
@Override public Uri insert(Uri uri, ContentValues values) { // TODO Auto-generated method stub Log.e("appstore insert", "uri is " + uri.toString()); String serviceURL = (String) values.get("serviceURL"); int eventType = (Integer) values.get("eventType"); String deviceUser = (String) values.get("deviceUser"); String operationResult = (String) values.get("operationResult"); String operationDesc = (String) values.get("operationDesc"); String createDate = (String) values.get("createDate"); Log.e("appstore insert", "serviceURL is " + serviceURL); Log.e("appstore insert", "eventType is " + eventType); Log.e("appstore insert", "deviceUser is " + deviceUser); Log.e("appstore insert", "operationResult is " + operationResult); Log.e("appstore insert", "operationDesc is " + operationDesc); Log.e("appstore insert", "createDate is " + createDate); historyDatabase.insert(TABLE_HISTORY, null, values); return null; }