List of usage examples for android.database SQLException SQLException
public SQLException(String error)
From source file:edu.mit.media.funf.pipeline.BasicPipeline.java
protected void writeData(String name, IJsonObject data) { SQLiteDatabase db = databaseHelper.getWritableDatabase(); final double timestamp = data.get(ProbeKeys.BaseProbeKeys.TIMESTAMP).getAsDouble(); final String value = data.toString(); if (timestamp == 0L || name == null || value == null) { Log.e(LogUtil.TAG, "Unable to save data. Not all required values specified. " + timestamp + " " + name + " - " + value); throw new SQLException("Not all required fields specified."); }//w w w .ja va 2 s. c o m String[] subStrings = name.split("\\."); String probeName = subStrings[subStrings.length - 1]; ContentValues cv = new ContentValues(); cv.put(DatabaseHelper.TABLE_STANDARD_PROBE, name); cv.put(DatabaseHelper.TABLE_STANDARD_VALUE, data.toString()); cv.put(DatabaseHelper.TABLE_STANDARD_TIMESTAMP, TimeUtil.alignedTimestamp); for (String entry : data.getAllKeys()) if (DatabaseHelper.getAllowedList().contains(entry.toLowerCase(Locale.ENGLISH))) { String toSave = data.toString(); try { toSave = data.get(entry).getAsString(); } catch (Exception e) { e.printStackTrace(); } cv.put(entry, toSave); } db.insertOrThrow(probeName, "", cv); Log.e("Database", name + " " + TimeUtil.alignedTimestamp); Intent intent = new Intent("pipeline"); intent.putExtra("Name", name); intent.putExtra("IJsonObject", data.toString()); // intent.setAction("edu.mit.media.funf.pipeline.broadcastreceiver"); LocalBroadcastManager.getInstance(getFunfManager()).sendBroadcast(intent); db.close(); }
From source file:com.manning.androidhacks.hack023.provider.TodoContentProvider.java
@Override public Uri insert(Uri uri, ContentValues initialValues) { ContentValues values;/* w w w .ja va 2s . com*/ if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } String table = null; String nullableCol = null; switch (sUriMatcher.match(uri)) { case TODO: table = TODO_TABLE_NAME; nullableCol = COLUMN_TITLE; break; default: new RuntimeException("Invalid URI for inserting: " + uri); } SQLiteDatabase db = dbHelper.getWritableDatabase(); long rowId = db.insert(table, nullableCol, values); if (rowId > 0) { Uri noteUri = ContentUris.withAppendedId(uri, rowId); getContext().getContentResolver().notifyChange(noteUri, null); return noteUri; } throw new SQLException("Failed to insert row into " + uri); }
From source file:org.opendatakit.services.instance.provider.InstanceProvider.java
@Override public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {// w w w . jav a 2s. co m possiblyWaitForContentProviderDebugger(); List<String> segments = uri.getPathSegments(); if (segments.size() < 2 || segments.size() > 3) { throw new SQLException("Unknown URI (too many segments!) " + uri); } String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); String tableId = segments.get(1); DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .generateInternalUseDbHandle(); boolean success = false; OdkConnectionInterface db = null; try { // +1 referenceCount if db is returned (non-null) db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(appName, dbHandleName); Cursor c = db.query(tableId, projection, selection, selectionArgs, null, null, sortOrder, null); if (c == null) { return null; } // Tell the cursor what uri to watch, so it knows when its source data // changes c.setNotificationUri(getContext().getContentResolver(), uri); c.registerDataSetObserver(new InvalidateMonitor(appName, dbHandleName)); success = true; return c; } finally { if (db != null) { try { db.releaseReference(); } finally { if (!success) { // this closes the connection // if it was successful, then the InvalidateMonitor will close the connection OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().removeConnection(appName, dbHandleName); } } } } }
From source file:com.example.android.notepad.CMNotesProvider.java
@Override public Uri insert(Uri uri, ContentValues initialValues) { // Validate the requested uri if (sUriMatcher.match(uri) != NOTES) { throw new IllegalArgumentException("Unknown URI " + uri); }/* w w w. j a va 2s . c om*/ ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } Long now = Long.valueOf(System.currentTimeMillis()); // Make sure that the fields are all set if (values.containsKey(NotePad.Notes.CREATED_DATE) == false) { values.put(NotePad.Notes.CREATED_DATE, now); } if (values.containsKey(NotePad.Notes.MODIFIED_DATE) == false) { values.put(NotePad.Notes.MODIFIED_DATE, now); } if (values.containsKey(NotePad.Notes.TITLE) == false) { Resources r = Resources.getSystem(); values.put(NotePad.Notes.TITLE, r.getString(android.R.string.untitled)); } if (values.containsKey(NotePad.Notes.NOTE) == false) { values.put(NotePad.Notes.NOTE, ""); } CMAdapter cmadapter = new CMAdapter(); // for the moment, use time for the key String key = System.currentTimeMillis() + ""; String new_key = cmadapter.updateValue(key, values); if (new_key != null) { System.out.println("Set key: " + key + ", got key: " + new_key); Uri noteUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_URI, Long.parseLong(new_key)); getContext().getContentResolver().notifyChange(noteUri, null); return noteUri; } // SQLiteDatabase db = mOpenHelper.getWritableDatabase(); // long rowId = db.insert(NOTES_TABLE_NAME, Notes.NOTE, values); // if (rowId > 0) { // Uri noteUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_URI, rowId); // getContext().getContentResolver().notifyChange(noteUri, null); // return noteUri; // } throw new SQLException("Failed to insert row into " + uri); }
From source file:com.gsma.rcs.ri.utils.RcsContactUtil.java
/** * Gets the photo of a contact, or null if no photo is present * /* w w w .ja v a 2 s . c o m*/ * @param contact the contact ID * @return an Bitmap of the photo, or null if no photo is present */ public Bitmap getPhotoFromContactId(ContactId contact) { /* First try to get it from cache */ Bitmap photo = mPhotoContactCache.get(contact); if (photo != null) { return photo; } Uri contactUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, Uri.encode(contact.toString())); Cursor cursor = null; try { cursor = mResolver.query(contactUri, PROJ_CONTACT_ID, null, null, null); if (cursor == null) { throw new SQLException("Cannot query photo for contact=" + contact); } if (!cursor.moveToFirst()) { return null; } long contactId = cursor.getLong(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID)); InputStream photoInputStream = ContactsContract.Contacts.openContactPhotoInputStream(mResolver, ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId)); if (photoInputStream != null) { photo = BitmapFactory.decodeStream(photoInputStream); /* Insert in cache */ mPhotoContactCache.put(contact, photo); return photo; } return null; } finally { if (cursor != null) { cursor.close(); } } }
From source file:org.mozilla.labs.Soup.provider.AppsProvider.java
@Override public Uri insert(Uri uri, ContentValues initialValues) { // Validate the requested uri if (sUriMatcher.match(uri) != APPS) { throw new IllegalArgumentException("Unknown URI " + uri); }//w w w. j a v a 2 s . c o m ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } Long now = Long.valueOf(System.currentTimeMillis()); // Make sure that the fields are all set if (values.containsKey(AppsContract.Apps.CREATED_DATE) == false) { values.put(AppsContract.Apps.CREATED_DATE, now); } if (values.containsKey(AppsContract.Apps.MODIFIED_DATE) == false) { values.put(AppsContract.Apps.MODIFIED_DATE, now); } if (values.containsKey(AppsContract.Apps.INSTALL_TIME) == false) { values.put(AppsContract.Apps.INSTALL_TIME, now); } if (values.containsKey(AppsContract.Apps.NAME) == false) { Resources r = Resources.getSystem(); values.put(AppsContract.Apps.NAME, r.getString(android.R.string.untitled)); } if (values.containsKey(AppsContract.Apps.DESCRIPTION) == false) { values.put(AppsContract.Apps.DESCRIPTION, ""); } if (values.containsKey(AppsContract.Apps.MANIFEST) == false) { values.put(AppsContract.Apps.MANIFEST, new JSONObject().toString()); } if (values.containsKey(AppsContract.Apps.MANIFEST_URL) == false) { values.put(AppsContract.Apps.MANIFEST_URL, ""); } if (values.containsKey(AppsContract.Apps.INSTALL_DATA) == false) { values.put(AppsContract.Apps.INSTALL_DATA, new JSONObject().toString()); } if (values.containsKey(AppsContract.Apps.STATUS) == false) { values.put(AppsContract.Apps.STATUS, 0); } SQLiteDatabase db = mOpenHelper.getWritableDatabase(); long rowId = db.insert(APPS_TABLE_NAME, null, values); if (rowId > 0) { Uri appUri = ContentUris.withAppendedId(AppsContract.Apps.CONTENT_URI, rowId); getContext().getContentResolver().notifyChange(appUri, null); return appUri; } throw new SQLException("Failed to insert row into " + uri); }
From source file:org.opendatakit.services.instance.provider.InstanceProvider.java
/** * Update the status columns for the instance upload table * * @param db/*from ww w.j a v a2s . com*/ * @param uri * @param appName * @param tableId */ void internalUpdate(OdkConnectionInterface db, Uri uri, String appName, String tableId) { String instanceName = null; Cursor c = null; StringBuilder b = new StringBuilder(); try { 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); } try { c = db.query(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, new String[] { KeyValueStoreColumns.VALUE }, KeyValueStoreColumns.TABLE_ID + "=? AND " + KeyValueStoreColumns.PARTITION + "=? AND " + KeyValueStoreColumns.ASPECT + "=? AND " + KeyValueStoreColumns.KEY + "=?", new String[] { tableId, KeyValueStoreConstants.PARTITION_TABLE, KeyValueStoreConstants.ASPECT_DEFAULT, KeyValueStoreConstants.XML_INSTANCE_NAME }, null, null, null, null); if (c != null) { c.moveToFirst(); if (c.getCount() == 1) { int idxInstanceName = c.getColumnIndex(KeyValueStoreColumns.VALUE); instanceName = c.getString(idxInstanceName); } } } finally { if (c != null) { c.close(); } } // ARGH! we must ensure that we have records in our UPLOADS_TABLE_NAME // for every distinct instance in the data table. b.setLength(0); //@formatter:off b.append("INSERT INTO ").append(DatabaseConstants.UPLOADS_TABLE_NAME).append("(") .append(InstanceColumns.DATA_INSTANCE_ID).append(",") .append(InstanceColumns.DATA_TABLE_TABLE_ID).append(",").append("SELECT ") .append(InstanceColumns.DATA_INSTANCE_ID).append(",") .append(InstanceColumns.DATA_TABLE_TABLE_ID).append(",").append(" FROM (") .append("SELECT DISTINCT ").append(DATA_TABLE_ID_COLUMN).append(" as ") .append(InstanceColumns.DATA_INSTANCE_ID).append(",").append("? as ") .append(InstanceColumns.DATA_TABLE_TABLE_ID).append(" FROM ").append(tableId) .append(" EXCEPT SELECT DISTINCT ").append(InstanceColumns.DATA_INSTANCE_ID).append(",") .append(InstanceColumns.DATA_TABLE_TABLE_ID).append(" FROM ") .append(DatabaseConstants.UPLOADS_TABLE_NAME).append(")"); //@formatter:on String[] args = { tableId }; db.execSQL(b.toString(), args); //@formatter:off b.append("WITH idname AS (SELECT t.").append(DATA_TABLE_ID_COLUMN).append(" as ") .append(InstanceColumns.DATA_INSTANCE_ID).append(", t."); if (instanceName == null) { b.append(DataTableColumns.SAVEPOINT_TIMESTAMP); } else { b.append(instanceName); } b.append(" as ").append(InstanceColumns.DATA_INSTANCE_NAME).append(" FROM ").append(tableId) .append(" t WHERE t.").append(DataTableColumns.SAVEPOINT_TIMESTAMP).append("=") .append("(select max(v.").append(DataTableColumns.SAVEPOINT_TIMESTAMP).append(") from ") .append(tableId).append(" as v where v._id=t._id)").append(") UPDATE ") .append(DatabaseConstants.UPLOADS_TABLE_NAME).append(" SET ") .append(InstanceColumns.DATA_INSTANCE_NAME).append("=idname.") .append(InstanceColumns.DATA_INSTANCE_NAME).append(" WHERE ") .append(InstanceColumns.DATA_TABLE_TABLE_ID).append("=? AND ") .append(InstanceColumns.DATA_INSTANCE_ID).append("=idname.") .append(InstanceColumns.DATA_INSTANCE_ID); //@formatter:on db.execSQL(b.toString(), args); db.setTransactionSuccessful(); } finally { db.endTransaction(); } }
From source file:com.gsma.rcs.ri.messaging.chat.single.SingleChatIntentService.java
/** * Get set of undelivered messages//from w w w .java 2 s. c om * * @param ctx The context * @param contact The contact * @return set of undelivered messages */ public static Set<String> getUndelivered(Context ctx, ContactId contact) { Set<String> messageIds = new HashSet<>(); Cursor cursor = null; try { cursor = ctx.getContentResolver().query(ChatLog.Message.CONTENT_URI, PROJ_UNDELIVERED_MSG, SEL_UNDELIVERED_MESSAGES, new String[] { contact.toString() }, null); if (cursor == null) { throw new SQLException("Cannot query undelivered message for contact=" + contact); } if (!cursor.moveToFirst()) { return messageIds; } int messageIdColumnIdx = cursor.getColumnIndexOrThrow(ChatLog.Message.MESSAGE_ID); do { messageIds.add(cursor.getString(messageIdColumnIdx)); } while (cursor.moveToNext()); return messageIds; } finally { if (cursor != null) { cursor.close(); } } }
From source file:com.gsma.rcs.ri.messaging.filetransfer.FileTransferIntentService.java
/** * Get set of undelivered file transfers * * @param ctx The context//from w ww .ja v a 2s . c om * @param contact The contact * @return set of undelivered file transfers */ public static Set<String> getUndelivered(Context ctx, ContactId contact) { Set<String> ids = new HashSet<>(); Cursor cursor = null; try { cursor = ctx.getContentResolver().query(FileTransferLog.CONTENT_URI, PROJ_UNDELIVERED_FT, SEL_UNDELIVERED_FTS, new String[] { contact.toString() }, null); if (cursor == null) { throw new SQLException("Cannot query undelivered file transfers for contact=" + contact); } if (!cursor.moveToFirst()) { return ids; } int idColumnIdx = cursor.getColumnIndexOrThrow(FileTransferLog.FT_ID); do { ids.add(cursor.getString(idColumnIdx)); } while (cursor.moveToNext()); return ids; } finally { if (cursor != null) { cursor.close(); } } }
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); }/*from w w w.j a va2 s.c o m*/ 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); } } } } }