List of usage examples for android.content ContentValues keySet
public Set<String> keySet()
From source file:org.opendatakit.services.forms.provider.FormsProvider.java
@Override public synchronized Uri insert(@NonNull Uri uri, ContentValues initialValues) { possiblyWaitForContentProviderDebugger(); List<String> segments = uri.getPathSegments(); if (segments.size() != 1) { throw new IllegalArgumentException("Unknown URI (too many segments!) " + uri); }/*w w w . j a va 2s . com*/ String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); WebLoggerIf log = WebLogger.getLogger(appName); HashMap<String, Object> values = new HashMap<String, Object>(); if (initialValues != null) { for (String key : initialValues.keySet()) { values.put(key, initialValues.get(key)); } } // force a scan from disk values.remove(FormsColumns.DATE); values.remove(FormsColumns.JSON_MD5_HASH); FormSpec formSpec = patchUpValues(appName, values); // first try to see if a record with this filename already exists... String[] projection = { FormsColumns.TABLE_ID, FormsColumns.FORM_ID }; String selection = FormsColumns.TABLE_ID + "=? AND " + FormsColumns.FORM_ID + "=?"; String[] selectionArgs = { formSpec.tableId, formSpec.formId }; Cursor c = null; DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .generateInternalUseDbHandle(); OdkConnectionInterface db = null; try { // +1 referenceCount if db is returned (non-null) db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(appName, dbHandleName); db.beginTransactionNonExclusive(); try { c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, selection, selectionArgs, null, null, null, null); if (c == null) { throw new SQLException( "FAILED Insert into " + uri + " -- unable to query for existing records. tableId=" + formSpec.tableId + " formId=" + formSpec.formId); } c.moveToFirst(); if (c.getCount() > 0) { // already exists throw new SQLException("FAILED Insert into " + uri + " -- row already exists for tableId=" + formSpec.tableId + " formId=" + formSpec.formId); } } catch (Exception e) { log.w(t, "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString()); if (e instanceof SQLException) { throw (SQLException) e; } else { throw new SQLException( "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString()); } } finally { if (c != null) { c.close(); } } try { long rowId = db.insertOrThrow(DatabaseConstants.FORMS_TABLE_NAME, null, values); db.setTransactionSuccessful(); // and notify listeners of the new row... Uri formUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), (String) values.get(FormsColumns.FORM_ID)); getContext().getContentResolver().notifyChange(formUri, null); Uri idUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), Long.toString(rowId)); getContext().getContentResolver().notifyChange(idUri, null); return formUri; } catch (Exception e) { log.w(t, "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString()); if (e instanceof SQLException) { throw (SQLException) e; } else { throw new SQLException( "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString()); } } } catch (SQLException e) { throw e; } catch (Exception e) { throw new SQLException("FAILED Insert into " + uri + " -- insert of row failed: " + e.toString()); } finally { if (db != null) { try { if (db.inTransaction()) { db.endTransaction(); } } finally { try { db.releaseReference(); } finally { // this closes the connection OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().removeConnection(appName, dbHandleName); } } } } }
From source file:com.openerp.orm.ORM.java
/** * Creates the record onserver.//from ww w. j a v a2 s . c o m * * @param dbHelper * the db helper * @param values * the values * @return the int */ public int createRecordOnserver(BaseDBHelper dbHelper, ContentValues values) { String model = dbHelper.getModelName(); int newId = 0; try { JSONObject arguments = new JSONObject(); for (String key : values.keySet()) { arguments.put(key, values.get(key)); } newId = oe_obj.createNew(model, arguments).getInt("result"); } catch (Exception e) { } return newId; }
From source file:com.android.contacts.ContactSaveService.java
private void createRawContact(Intent intent) { String accountName = intent.getStringExtra(EXTRA_ACCOUNT_NAME); String accountType = intent.getStringExtra(EXTRA_ACCOUNT_TYPE); String dataSet = intent.getStringExtra(EXTRA_DATA_SET); List<ContentValues> valueList = intent.getParcelableArrayListExtra(EXTRA_CONTENT_VALUES); Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT); ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(); operations.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI) .withValue(RawContacts.ACCOUNT_NAME, accountName).withValue(RawContacts.ACCOUNT_TYPE, accountType) .withValue(RawContacts.DATA_SET, dataSet).build()); int size = valueList.size(); for (int i = 0; i < size; i++) { ContentValues values = valueList.get(i); values.keySet().retainAll(ALLOWED_DATA_COLUMNS); operations.add(ContentProviderOperation.newInsert(Data.CONTENT_URI) .withValueBackReference(Data.RAW_CONTACT_ID, 0).withValues(values).build()); }/*from www. j a v a 2s.co m*/ ContentResolver resolver = getContentResolver(); ContentProviderResult[] results; try { results = resolver.applyBatch(ContactsContract.AUTHORITY, operations); } catch (Exception e) { throw new RuntimeException("Failed to store new contact", e); } Uri rawContactUri = results[0].uri; callbackIntent.setData(RawContacts.getContactLookupUri(resolver, rawContactUri)); deliverCallback(callbackIntent); }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * If the caller specified a complex json value for a structured type, flush * the value through to the individual columns. * /*from w w w . j av a 2 s . co m*/ * @param orderedColumns * @param values */ private void cleanUpValuesMap(ArrayList<ColumnDefinition> orderedColumns, ContentValues values) { Map<String, String> toBeResolved = new HashMap<String, String>(); for (String key : values.keySet()) { if (DataTableColumns.CONFLICT_TYPE.equals(key)) { continue; } else if (DataTableColumns.FILTER_TYPE.equals(key)) { continue; } else if (DataTableColumns.FILTER_TYPE.equals(key)) { continue; } else if (DataTableColumns.FILTER_VALUE.equals(key)) { continue; } else if (DataTableColumns.FORM_ID.equals(key)) { continue; } else if (DataTableColumns.ID.equals(key)) { continue; } else if (DataTableColumns.LOCALE.equals(key)) { continue; } else if (DataTableColumns.ROW_ETAG.equals(key)) { continue; } else if (DataTableColumns.SAVEPOINT_CREATOR.equals(key)) { continue; } else if (DataTableColumns.SAVEPOINT_TIMESTAMP.equals(key)) { continue; } else if (DataTableColumns.SAVEPOINT_TYPE.equals(key)) { continue; } else if (DataTableColumns.SYNC_STATE.equals(key)) { continue; } else if (DataTableColumns._ID.equals(key)) { continue; } // OK it is one of the data columns ColumnDefinition cp = ColumnDefinition.find(orderedColumns, key); if (!cp.isUnitOfRetention()) { toBeResolved.put(key, values.getAsString(key)); } } // remove these non-retained values from the values set... for (String key : toBeResolved.keySet()) { values.remove(key); } while (!toBeResolved.isEmpty()) { Map<String, String> moreToResolve = new HashMap<String, String>(); for (Map.Entry<String, String> entry : toBeResolved.entrySet()) { String key = entry.getKey(); String json = entry.getValue(); if (json == null) { // don't need to do anything // since the value is null continue; } ColumnDefinition cp = ColumnDefinition.find(orderedColumns, key); try { Map<String, Object> struct = ODKFileUtils.mapper.readValue(json, Map.class); for (ColumnDefinition child : cp.getChildren()) { String subkey = child.getElementKey(); ColumnDefinition subcp = ColumnDefinition.find(orderedColumns, subkey); if (subcp.isUnitOfRetention()) { ElementType subtype = subcp.getType(); ElementDataType type = subtype.getDataType(); if (type == ElementDataType.integer) { values.put(subkey, (Integer) struct.get(subcp.getElementName())); } else if (type == ElementDataType.number) { values.put(subkey, (Double) struct.get(subcp.getElementName())); } else if (type == ElementDataType.bool) { values.put(subkey, ((Boolean) struct.get(subcp.getElementName())) ? 1 : 0); } else { values.put(subkey, (String) struct.get(subcp.getElementName())); } } else { // this must be a javascript structure... re-JSON it and save (for // next round). moreToResolve.put(subkey, ODKFileUtils.mapper.writeValueAsString(struct.get(subcp.getElementName()))); } } } catch (JsonParseException e) { e.printStackTrace(); throw new IllegalStateException("should not be happening"); } catch (JsonMappingException e) { e.printStackTrace(); throw new IllegalStateException("should not be happening"); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("should not be happening"); } } toBeResolved = moreToResolve; } }
From source file:com.android.mail.browse.ConversationCursor.java
/** * Returns a Conversation object for the current position, or null if it has not yet been * cached.//from ww w. j a v a 2s . c om * * This method will apply any cached column data to the result. * */ public Conversation getCachedConversation() { Conversation result = mUnderlyingCursor.getConversation(); if (result == null) { return null; } // apply any cached values // but skip over any cached values that aren't part of the cursor projection final ContentValues values = mCacheMap.get(mUnderlyingCursor.getInnerUri()); if (values != null) { final ContentValues queryableValues = new ContentValues(); for (String key : values.keySet()) { if (!mColumnNameSet.contains(key)) { continue; } putInValues(queryableValues, key, values.get(key)); } if (queryableValues.size() > 0) { // copy-on-write to help ensure the underlying cached Conversation is immutable // of course, any callers this method should also try not to modify them // overmuch... result = new Conversation(result); result.applyCachedValues(queryableValues); } } return result; }
From source file:com.tct.mail.browse.ConversationCursor.java
/** * Returns a Conversation object for the current position, or null if it has not yet been * cached.//www.j av a 2s . c o m * * This method will apply any cached column data to the result. * */ public Conversation getCachedConversation() { Conversation result = mUnderlyingCursor.getConversation(); if (result == null) { return null; } // apply any cached values // but skip over any cached values that aren't part of the cursor projection // TS: zhaotianyong 2015-01-27 EMAIL BUGFIX-912291 MOD_S if (mUnderlyingCursor.getInnerUri() != null) { final ContentValues values = mCacheMap.get(mUnderlyingCursor.getInnerUri()); if (values != null) { final ContentValues queryableValues = new ContentValues(); for (String key : values.keySet()) { if (!mColumnNameSet.contains(key)) { continue; } putInValues(queryableValues, key, values.get(key)); } if (queryableValues.size() > 0) { // copy-on-write to help ensure the underlying cached Conversation is immutable // of course, any callers this method should also try not to modify them // overmuch... result = new Conversation(result); result.applyCachedValues(queryableValues); } } } // TS: zhaotianyong 2015-01-27 EMAIL BUGFIX-912291 MOD_E return result; }
From source file:com.openerp.orm.ORM.java
/** * Write./*from ww w . jav a2 s . c o m*/ * * @param dbHelper * the db helper * @param values * the values * @param id * the id * @param fromServer * the from server * @return true, if successful */ public boolean write(BaseDBHelper dbHelper, ContentValues values, int id, boolean fromServer) { // Handling many2one records HashMap<String, Object> many2onecols = dbHelper.getMany2OneColumns(); // Handling Many2Many Records HashMap<String, Object> many2manycols = dbHelper.getMany2ManyColumns(); for (String key : many2manycols.keySet()) { try { JSONArray m2mArray = new JSONArray(values.getAsString(key)); Many2Many m2m = (Many2Many) many2manycols.get(key); updateM2MRecords(values.getAsString("id"), m2mArray, key, dbHelper, m2m, values); } catch (Exception e) { } values.remove(key); } // Handling many2one records. [id, "name"] to id for (String key : many2onecols.keySet()) { try { String tempVals = values.getAsString(key); if (!tempVals.equals("false")) { JSONArray m2oArray = new JSONArray(values.getAsString(key)); int m2oid = m2oArray.getInt(0); values.put(key, m2oid); } else { values.put(key, "false"); } } catch (Exception e) { } } boolean flag = false; SQLiteDatabase db = getWritableDatabase(); try { if (OpenERPServerConnection.isNetworkAvailable(context)) { String table = modelToTable(dbHelper.getModelName()); try { JSONObject arguments = new JSONObject(); for (String key : values.keySet()) { try { int keyid = Integer.parseInt(values.getAsString(key)); arguments.put(key, keyid); } catch (Exception e) { String temp = values.getAsString(key); if (temp.equals("true") || temp.equals("false")) { arguments.put(key, ((temp.equals("true")) ? true : false)); } else { arguments.put(key, values.get(key).toString()); } } } if (fromServer) { int res = db.update(table, values, "id = " + id, null); flag = true; } else { if (oe_obj.updateValues(dbHelper.getModelName(), arguments, id)) { int res = db.update(table, values, "id = " + id, null); flag = true; } } } catch (Exception e) { e.printStackTrace(); flag = false; } } else { Toast.makeText(context, "Unable to Connect server ! Please Try again Later. ", Toast.LENGTH_LONG) .show(); flag = false; } } catch (Exception e) { } db.close(); return flag; }
From source file:org.opendatakit.services.instance.provider.InstanceProvider.java
@Override public synchronized int update(@NonNull Uri uri, ContentValues cv, String where, String[] whereArgs) { possiblyWaitForContentProviderDebugger(); List<String> segments = uri.getPathSegments(); if (segments.size() != 3) { throw new SQLException("Unknown URI (does not specify instance!) " + uri); }/*from w ww. j a v a 2 s.c o m*/ 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); DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .generateInternalUseDbHandle(); OdkConnectionInterface db = null; int count = 0; try { // +1 referenceCount if db is returned (non-null) db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(appName, dbHandleName); db.beginTransactionNonExclusive(); boolean success = false; try { success = ODKDatabaseImplUtils.get().hasTableId(db, tableId); } catch (Exception e) { WebLogger.getLogger(appName).printStackTrace(e); throw new SQLException("Unknown URI (exception testing for tableId) " + uri); } if (!success) { throw new SQLException("Unknown URI (missing data table for tableId) " + uri); } internalUpdate(db, uri, appName, 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 = internalQuery(db, uri, appName, tableId, instanceId, null, where, whereArgs, null); ref.moveToFirst(); if (ref.getCount() != 0) { do { String iId = CursorUtils.getIndexAsString(ref, ref.getColumnIndex(InstanceColumns._ID)); String iIdDataTable = CursorUtils.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 (cv.containsKey(InstanceColumns.XML_PUBLISH_STATUS)) { Date xmlPublishDate = new Date(); cv.put(InstanceColumns.XML_PUBLISH_TIMESTAMP, TableConstants.nanoSecondsFromMillis(xmlPublishDate.getTime())); String xmlPublishStatus = cv.getAsString(InstanceColumns.XML_PUBLISH_STATUS); if (!cv.containsKey(InstanceColumns.DISPLAY_SUBTEXT)) { String text = getDisplaySubtext(xmlPublishStatus, xmlPublishDate); cv.put(InstanceColumns.DISPLAY_SUBTEXT, text); } } Map<String, Object> values = new HashMap<String, Object>(); for (String key : cv.keySet()) { values.put(key, cv.get(key)); } Object[] 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) { try { if (db.inTransaction()) { db.endTransaction(); } } finally { try { db.releaseReference(); } finally { // this closes the connection OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().removeConnection(appName, dbHandleName); } } } } getContext().getContentResolver().notifyChange(uri, null); return count; }
From source file:org.opendatakit.services.forms.provider.FormsProvider.java
@Override public synchronized int update(@NonNull Uri uri, ContentValues values, String where, String[] whereArgs) { possiblyWaitForContentProviderDebugger(); List<String> segments = uri.getPathSegments(); PatchedFilter pf = extractUriFeatures(uri, segments, where, whereArgs); WebLoggerIf logger = WebLogger.getLogger(pf.appName); /*//ww w .j a va2s . c o m * First, find out what records match this query. Replicate the * ContentValues if there are multiple tableIds/formIds involved * and the contentValues do not have formId and tableId specified. * * Otherwise, it is an error to specify the tableId or formId in * the ContentValues and have those not match the where results. * */ String contentTableId = (values != null && values.containsKey(FormsColumns.TABLE_ID)) ? values.getAsString(FormsColumns.TABLE_ID) : null; String contentFormId = (values != null && values.containsKey(FormsColumns.FORM_ID)) ? values.getAsString(FormsColumns.FORM_ID) : null; HashMap<FormSpec, HashMap<String, Object>> matchedValues = new HashMap<FormSpec, HashMap<String, Object>>(); DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .generateInternalUseDbHandle(); OdkConnectionInterface db = null; try { // +1 referenceCount if db is returned (non-null) db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(pf.appName, dbHandleName); db.beginTransactionNonExclusive(); Cursor c = null; try { c = db.query(DatabaseConstants.FORMS_TABLE_NAME, null, pf.whereId, pf.whereIdArgs, null, null, null, null); if (c == null) { throw new SQLException( "FAILED Update of " + uri + " -- query for existing row did not return a cursor"); } if (c.moveToFirst()) { int idxId = c.getColumnIndex(FormsColumns._ID); int idxTableId = c.getColumnIndex(FormsColumns.TABLE_ID); int idxFormId = c.getColumnIndex(FormsColumns.FORM_ID); Integer idValue = null; String tableIdValue = null; String formIdValue = null; do { idValue = CursorUtils.getIndexAsType(c, Integer.class, idxId); tableIdValue = CursorUtils.getIndexAsString(c, idxTableId); formIdValue = CursorUtils.getIndexAsString(c, idxFormId); if (contentTableId != null && !contentTableId.equals(tableIdValue)) { throw new SQLException("Modification of tableId for an existing form is prohibited"); } if (contentFormId != null && !contentFormId.equals(formIdValue)) { throw new SQLException("Modification of formId for an existing form is prohibited"); } HashMap<String, Object> cv = new HashMap<String, Object>(); if (values != null) { for (String key : values.keySet()) { cv.put(key, values.get(key)); } } cv.put(FormsColumns.TABLE_ID, tableIdValue); cv.put(FormsColumns.FORM_ID, formIdValue); for (int idx = 0; idx < c.getColumnCount(); ++idx) { String colName = c.getColumnName(idx); if (colName.equals(FormsColumns._ID)) { // don't insert the PK continue; } if (c.isNull(idx)) { cv.put(colName, null); } else { // everything else, we control... Class<?> dataType = CursorUtils.getIndexDataType(c, idx); if (dataType == String.class) { cv.put(colName, CursorUtils.getIndexAsString(c, idx)); } else if (dataType == Long.class) { cv.put(colName, CursorUtils.getIndexAsType(c, Long.class, idx)); } else if (dataType == Double.class) { cv.put(colName, CursorUtils.getIndexAsType(c, Double.class, idx)); } } } FormSpec formSpec = patchUpValues(pf.appName, cv); formSpec._id = idValue.toString(); formSpec.success = false; matchedValues.put(formSpec, cv); } while (c.moveToNext()); } else { // no match on where clause... return 0; } } finally { if (c != null && !c.isClosed()) { c.close(); } } // go through the entries and update the database with these patched-up values... for (Entry<FormSpec, HashMap<String, Object>> e : matchedValues.entrySet()) { FormSpec fs = e.getKey(); HashMap<String, Object> cv = e.getValue(); if (db.update(DatabaseConstants.FORMS_TABLE_NAME, cv, FormsColumns._ID + "=?", new String[] { fs._id }) > 0) { fs.success = true; } } db.setTransactionSuccessful(); } catch (Exception e) { logger.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 (db != null) { try { if (db.inTransaction()) { db.endTransaction(); } } finally { try { db.releaseReference(); } finally { // this closes the connection OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .removeConnection(pf.appName, dbHandleName); } } } } int failureCount = 0; for (FormSpec fs : matchedValues.keySet()) { if (fs.success) { Uri formUri = Uri .withAppendedPath( Uri.withAppendedPath(Uri.withAppendedPath( Uri.parse("content://" + getFormsAuthority()), pf.appName), fs.tableId), fs.formId); getContext().getContentResolver().notifyChange(formUri, null); Uri idUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), pf.appName), fs._id); getContext().getContentResolver().notifyChange(idUri, null); } else { ++failureCount; } } getContext().getContentResolver().notifyChange(uri, null); int count = matchedValues.size(); if (failureCount != 0) { throw new SQLiteException( "Unable to update all forms (" + (count - failureCount) + " of " + count + " updated)"); } return count; }
From source file:org.opendatakit.services.database.utlities.ODKDatabaseImplUtils.java
/** * Insert a row into a local only table// w w w. j av a 2s.c om * * @param db * @param tableId * @param rowValues * @throws ActionNotAuthorizedException */ public void insertLocalOnlyRow(OdkConnectionInterface db, String tableId, ContentValues rowValues) throws IllegalArgumentException { if (rowValues == null || rowValues.size() <= 0) { throw new IllegalArgumentException(t + ": No values to add into table " + tableId); } HashMap<String, Object> cvDataTableVal = new HashMap<String, Object>(); for (String key : rowValues.keySet()) { cvDataTableVal.put(key, rowValues.get(key)); } boolean dbWithinTransaction = db.inTransaction(); try { if (!dbWithinTransaction) { db.beginTransactionNonExclusive(); } db.insertOrThrow(tableId, null, cvDataTableVal); if (!dbWithinTransaction) { db.setTransactionSuccessful(); } } finally { if (!dbWithinTransaction) { db.endTransaction(); } } }