List of usage examples for android.net Uri withAppendedPath
public static Uri withAppendedPath(Uri baseUri, String pathSegment)
From source file:org.opendatakit.common.android.task.InitializationTask.java
/** * Scan the given formDir and update the Forms database. If it is the * formsFolder, then any 'framework' forms should be forbidden. If it is not * the formsFolder, only 'framework' forms should be allowed * * @param tableId//from w w w . j a v a 2s .co m * @param formId * @param formDir * @param isFormsFolder * @param baseStaleMediaPath -- path prefix to the stale forms/framework directory. */ private final void updateFormDir(String tableId, String formId, File formDir, boolean isFormsFolder, String baseStaleMediaPath) { Uri formsProviderContentUri = Uri.parse("content://" + FormsProviderAPI.AUTHORITY); String formDirectoryPath = formDir.getAbsolutePath(); WebLogger.getLogger(appName).i(t, "updateFormDir: " + formDirectoryPath); String successMessage = appContext.getString(R.string.form_register_success, tableId, formId); String failureMessage = appContext.getString(R.string.form_register_failure, tableId, formId); Cursor c = null; try { String selection = FormsColumns.TABLE_ID + "=? AND " + FormsColumns.FORM_ID + "=?"; String[] selectionArgs = { tableId, formId }; c = appContext.getContentResolver().query(Uri.withAppendedPath(formsProviderContentUri, appName), null, selection, selectionArgs, null); if (c == null) { WebLogger.getLogger(appName).w(t, "updateFormDir: " + formDirectoryPath + " null cursor -- cannot update!"); mPendingResult.add(failureMessage); return; } if (c.getCount() > 1) { c.close(); WebLogger.getLogger(appName).w(t, "updateFormDir: " + formDirectoryPath + " multiple records from cursor -- delete all and restore!"); // we have multiple records for this one directory. // Rename the directory. Delete the records, and move the // directory back. File tempMediaPath = moveToStaleDirectory(formDir, baseStaleMediaPath); appContext.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName), selection, selectionArgs); FileUtils.moveDirectory(tempMediaPath, formDir); ContentValues cv = new ContentValues(); cv.put(FormsColumns.TABLE_ID, tableId); cv.put(FormsColumns.FORM_ID, formId); appContext.getContentResolver().insert(Uri.withAppendedPath(formsProviderContentUri, appName), cv); } else if (c.getCount() == 1) { c.close(); ContentValues cv = new ContentValues(); cv.put(FormsColumns.TABLE_ID, tableId); cv.put(FormsColumns.FORM_ID, formId); appContext.getContentResolver().update(Uri.withAppendedPath(formsProviderContentUri, appName), cv, null, null); } else if (c.getCount() == 0) { c.close(); ContentValues cv = new ContentValues(); cv.put(FormsColumns.TABLE_ID, tableId); cv.put(FormsColumns.FORM_ID, formId); appContext.getContentResolver().insert(Uri.withAppendedPath(formsProviderContentUri, appName), cv); } } catch (IOException e) { WebLogger.getLogger(appName).printStackTrace(e); WebLogger.getLogger(appName).e(t, "updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); mPendingResult.add(failureMessage); return; } catch (IllegalArgumentException e) { WebLogger.getLogger(appName).printStackTrace(e); WebLogger.getLogger(appName).e(t, "updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); try { FileUtils.deleteDirectory(formDir); WebLogger.getLogger(appName).i(t, "updateFormDir: " + formDirectoryPath + " Removing -- unable to parse formDef file: " + e.toString()); } catch (IOException e1) { WebLogger.getLogger(appName).printStackTrace(e1); WebLogger.getLogger(appName) .i(t, "updateFormDir: " + formDirectoryPath + " Removing -- unable to delete form directory: " + formDir.getName() + " error: " + e.toString()); } mPendingResult.add(failureMessage); return; } catch (Exception e) { WebLogger.getLogger(appName).printStackTrace(e); WebLogger.getLogger(appName).e(t, "updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); mPendingResult.add(failureMessage); return; } finally { if (c != null && !c.isClosed()) { c.close(); } } mPendingResult.add(successMessage); }
From source file:com.android.email.activity.zx.MessageView.java
/** * Launch a thread (because of cross-process DB lookup) to check presence of the sender of the * message. When that thread completes, update the UI. * /*from w w w. j av a 2 s. c om*/ * This must only be called when mMessage is null (it will hide presence indications) or when * mMessage has already seen its headers loaded. * * Note: This is just a polling operation. A more advanced solution would be to keep the * cursor open and respond to presence status updates (in the form of content change * notifications). However, because presence changes fairly slowly compared to the duration * of viewing a single message, a simple poll at message load (and onResume) should be * sufficient. */ private void startPresenceCheck() { String email = null; try { if (mMessage != null) { Address sender = mMessage.getFrom()[0]; email = sender.getAddress(); } } catch (MessagingException me) { } if (email == null) { mHandler.setSenderPresence(0); return; } final String senderEmail = email; new Thread() { @Override public void run() { Cursor methodsCursor = getContentResolver().query( Uri.withAppendedPath(Contacts.ContactMethods.CONTENT_URI, "with_presence"), METHODS_WITH_PRESENCE_PROJECTION, Contacts.ContactMethods.DATA + "=?", new String[] { senderEmail }, null); int presenceIcon = 0; if (methodsCursor != null) { if (methodsCursor.moveToFirst() && !methodsCursor.isNull(METHODS_STATUS_COLUMN)) { } methodsCursor.close(); } mHandler.setSenderPresence(presenceIcon); } }.start(); }
From source file:com.android.contacts.ContactSaveService.java
/** * Save updated photo for the specified raw-contact. * @return true for success, false for failure *///from www. ja v a 2 s . c o m private boolean saveUpdatedPhoto(long rawContactId, Uri photoUri, int saveMode) { final Uri outputUri = Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.DisplayPhoto.CONTENT_DIRECTORY); return ContactPhotoUtils.savePhotoFromUriToUri(this, photoUri, outputUri, (saveMode == 0)); }
From source file:cx.ring.service.LocalService.java
@NonNull public static CallContact findContactByNumber(@NonNull ContentResolver res, String number) { //Log.w(TAG, "findContactByNumber " + number); CallContact c = null;/*from w w w. j a va 2s .co m*/ try { Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)); Cursor result = res.query(uri, PHONELOOKUP_PROJECTION, null, null, null); if (result == null) { Log.w(TAG, "findContactByNumber " + number + " can't find contact."); return findContactBySipNumber(res, number); } if (result.moveToFirst()) { int iID = result.getColumnIndex(ContactsContract.Contacts._ID); int iKey = result.getColumnIndex(ContactsContract.Data.LOOKUP_KEY); int iName = result.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); int iPhoto = result.getColumnIndex(ContactsContract.Contacts.PHOTO_ID); c = new CallContact(result.getLong(iID), result.getString(iKey), result.getString(iName), result.getLong(iPhoto)); lookupDetails(res, c); Log.w(TAG, "findContactByNumber " + number + " found " + c.getDisplayName()); } result.close(); } catch (Exception e) { Log.w(TAG, e); } if (c == null) { Log.w(TAG, "findContactByNumber " + number + " can't find contact."); c = findContactBySipNumber(res, number); } return c; }
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); /*//from w w w. ja v a 2 s . c om * 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.spontaneous.trackservice.RemoteService.java
/** * Use the ContentResolver mechanism to store a received location * * @param location//from ww w.j a va2 s.com */ private void storeLocation(Location location) { if (!isLogging()) { Log.e(TAG, String.format("Not logging but storing location %s, prepare to fail", location.toString())); } ContentValues args = new ContentValues(); args.put(Waypoints.LATITUDE, Double.valueOf(location.getLatitude())); args.put(Waypoints.LONGITUDE, Double.valueOf(location.getLongitude())); args.put(Waypoints.SPEED, Float.valueOf(location.getSpeed())); args.put(Waypoints.TIME, Long.valueOf(System.currentTimeMillis())); args.put(Waypoints.DISTANCE, this.mDistance); if (location.hasAccuracy()) { args.put(Waypoints.ACCURACY, Float.valueOf(location.getAccuracy())); } if (location.hasAltitude()) { args.put(Waypoints.ALTITUDE, Double.valueOf(location.getAltitude())); } if (location.hasBearing()) { args.put(Waypoints.BEARING, Float.valueOf(location.getBearing())); } Uri waypointInsertUri = Uri.withAppendedPath(Tracks.CONTENT_URI, this.mTrackId + "/segments/" + this.mSegmentId + "/waypoints"); Uri inserted = getContentResolver().insert(waypointInsertUri, args); this.mWaypointId = Long.parseLong(inserted.getLastPathSegment()); }
From source file:net.gsantner.opoc.util.ShareUtil.java
/** * Get content://media/ Uri for given file, or null if not indexed * * @param file Target file/*from w w w. ja va 2 s. c om*/ * @param mode 1 for picture, 2 for video, anything else for other * @return */ public Uri getMediaUri(File file, int mode) { Uri uri = MediaStore.Files.getContentUri("external"); uri = (mode != 0) ? (mode == 1 ? MediaStore.Images.Media.EXTERNAL_CONTENT_URI : MediaStore.Video.Media.EXTERNAL_CONTENT_URI) : uri; Cursor cursor = null; try { cursor = _context.getContentResolver().query(uri, new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "= ?", new String[] { file.getAbsolutePath() }, null); if (cursor != null && cursor.moveToFirst()) { int mediaid = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media._ID)); return Uri.withAppendedPath(uri, mediaid + ""); } } catch (Exception ignored) { } finally { if (cursor != null) { cursor.close(); } } return null; }
From source file:org.spontaneous.trackservice.RemoteService.java
/** * Update Track /* ww w . j a va2 s .c o m*/ * Store the current total distance of the track. * Store the current total duration of the track. */ private void updateTrack() { // Get current total duration TrackModel trackModel = readTrackAndSegmentsById(this.mTrackId); ContentValues args = new ContentValues(); args.put(TracksColumns.TOTAL_DISTANCE, this.mTotalDistance); args.put(TracksColumns.TOTAL_DURATION, TrackingUtil.computeTotalDuration(trackModel)); Uri trackUpdateUri = Uri.withAppendedPath(Tracks.CONTENT_URI, String.valueOf(this.mTrackId)); getContentResolver().update(trackUpdateUri, args, null, null); this.mTrackData = readTrackAndSegmentsById(this.mTrackId); }
From source file:edu.umbc.cs.ebiquity.mithril.parserapp.contentparsers.contacts.ContactsListFragment.java
/** * Decodes and scales a contact's image from a file pointed to by a Uri in the contact's data, * and returns the result as a Bitmap. The column that contains the Uri varies according to the * platform version.//from w w w . j a va2 s . c o m * * @param photoData For platforms prior to Android 3.0, provide the Contact._ID column value. * For Android 3.0 and later, provide the Contact.PHOTO_THUMBNAIL_URI value. * @param imageSize The desired target width and height of the output image in pixels. * @return A Bitmap containing the contact's image, resized to fit the provided image size. If * no thumbnail exists, returns null. */ private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) { // Ensures the Fragment is still added to an activity. As this method is called in a // background thread, there's the possibility the Fragment is no longer attached and // added to an activity. If so, no need to spend resources loading the contact photo. if (!isAdded() || getActivity() == null) { return null; } // Instantiates an AssetFileDescriptor. Given a content Uri pointing to an image file, the // ContentResolver can return an AssetFileDescriptor for the file. AssetFileDescriptor afd = null; // This "try" block catches an Exception if the file descriptor returned from the Contacts // Provider doesn't point to an existing file. try { Uri thumbUri; // If Android 3.0 or later, converts the Uri passed as a string to a Uri object. if (Utils.hasHoneycomb()) { thumbUri = Uri.parse(photoData); } else { // For versions prior to Android 3.0, appends the string argument to the content // Uri for the Contacts table. final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, photoData); // Appends the content Uri for the Contacts.Photo table to the previously // constructed contact Uri to yield a content URI for the thumbnail image thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY); } // Retrieves a file descriptor from the Contacts Provider. To learn more about this // feature, read the reference documentation for // ContentResolver#openAssetFileDescriptor. afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r"); // Gets a FileDescriptor from the AssetFileDescriptor. A BitmapFactory object can // decode the contents of a file pointed to by a FileDescriptor into a Bitmap. FileDescriptor fileDescriptor = afd.getFileDescriptor(); if (fileDescriptor != null) { // Decodes a Bitmap from the image pointed to by the FileDescriptor, and scales it // to the specified width and height return ImageLoader.decodeSampledBitmapFromDescriptor(fileDescriptor, imageSize, imageSize); } } catch (FileNotFoundException e) { // If the file pointed to by the thumbnail URI doesn't exist, or the file can't be // opened in "read" mode, ContentResolver.openAssetFileDescriptor throws a // FileNotFoundException. if (BuildConfig.DEBUG) { // Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData // + ": " + e.toString()); } } finally { // If an AssetFileDescriptor was returned, try to close it if (afd != null) { try { afd.close(); } catch (IOException e) { // Closing a file descriptor might cause an IOException if the file is // already closed. Nothing extra is needed to handle this. } } } // If the decoding failed, returns null return null; }
From source file:com.example.android.contactslist.ui.eventEntry.EventEntryFragment.java
@Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { switch (id) { // main queries to load the required information case ContactDetailQuery.QUERY_ID: // This query loads main contact details, see // ContactDetailQuery for more information. return new CursorLoader(getActivity(), mContactUri, ContactDetailQuery.PROJECTION, null, //ContactDetailQuery.SELECTION, null, //ContactDetailQuery.ARGS, null);//from w w w . jav a 2 s .co m case ContactAddressQuery.QUERY_ID: // This query loads contact address details, see // ContactAddressQuery for more information. final Uri uri = Uri.withAppendedPath(mContactUri, Contacts.Data.CONTENT_DIRECTORY); return new CursorLoader(getActivity(), uri, ContactAddressQuery.PROJECTION, ContactAddressQuery.SELECTION, null, null); case ContactStatsQuery.QUERY_ID: // This query loads data from ContactStatsContentProvider. //prepare the shere and args clause for the contact lookup key final String where = ContactStatsContract.TableEntry.KEY_CONTACT_KEY + " = ? "; String[] whereArgs = { mContactLookupKey }; return new CursorLoader(getActivity(), ContactStatsContentProvider.CONTACT_STATS_URI, null, where, whereArgs, null); case ContactVoiceNumberQuery.QUERY_ID: // get all the phone numbers for this contact, sorted by whether it is super primary // https://android.googlesource.com/platform/development/+/gingerbread/samples/ApiDemos/src/com/example/android/apis/view/List7.java return new CursorLoader(getActivity(), ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER }, //null ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY + " = ?", new String[] { mContactLookupKey }, ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY + " DESC"); case ContactSMSNumberQuery.QUERY_ID: // get all the phone numbers for this contact, sorted by whether it is super primary return new CursorLoader(getActivity(), ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER }, //null ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY + " = ? AND " + ContactsContract.CommonDataKinds.Phone.TYPE + " = ?", new String[] { mContactLookupKey, Integer.toString(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) }, ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY + " DESC"); case ContactEmailAddressQuery.QUERY_ID: // get all the phone numbers for this contact, sorted by whether it is super primary return new CursorLoader(getActivity(), ContactsContract.CommonDataKinds.Email.CONTENT_URI, new String[] { ContactsContract.CommonDataKinds.Email.ADDRESS }, //null ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY + " = ? ", new String[] { mContactLookupKey }, ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY + " DESC"); } return null; }