List of usage examples for android.net Uri withAppendedPath
public static Uri withAppendedPath(Uri baseUri, String pathSegment)
From source file:com.phonegap.ContactAccessorSdk3_4.java
/** * Takes a JSON contact object and loops through the available entries (Emails/IM's). If the * entry has an id that is not equal to null the entry will be updated in the database. * If the id is null then we treat it as a new entry. * /* w w w.j a v a 2 s.c o m*/ * @param contact the contact to extract the entries from * @param uri the base URI for this contact. */ private void saveEntries(JSONObject contact, Uri uri, String dataType, int contactKind) { ContentValues values = new ContentValues(); Uri newUri = Uri.withAppendedPath(uri, Contacts.People.ContactMethods.CONTENT_DIRECTORY); String id = null; try { JSONArray entries = contact.getJSONArray(dataType); if (entries != null && entries.length() > 0) { JSONObject entry; values.put(Contacts.ContactMethods.KIND, contactKind); for (int i = 0; i < entries.length(); i++) { entry = entries.getJSONObject(i); id = getJsonString(entry, "id"); values.put(Contacts.ContactMethods.DATA, getJsonString(entry, "value")); values.put(Contacts.ContactMethods.TYPE, getContactType(getJsonString(entry, "type"))); if (id == null) { Uri contactUpdate = mApp.getContentResolver().insert(newUri, values); } else { Uri tempUri = Uri.withAppendedPath(newUri, id); mApp.getContentResolver().update(tempUri, values, null, null); } } } } catch (JSONException e) { Log.d(LOG_TAG, "Could not save " + dataType + " = " + e.getMessage()); } }
From source file:com.example.contactslist.ui.ContactsListFragment.java
public void processCursor(Cursor data) { mAdapter.swapCursor(data);//from w w w . j a v a2 s .c o m // If this is a two-pane layout and there is a search query then // there is some additional work to do around default selected // search item. if (mIsTwoPaneLayout && !TextUtils.isEmpty(mSearchTerm) && mSearchQueryChanged) { // Selects the first item in results, unless this fragment has // been restored from a saved state (like orientation change) // in which case it selects the previously selected search item. if (data != null && data.moveToPosition(mPreviouslySelectedSearchItem)) { // Creates the content Uri for the previously selected contact by appending the // contact's ID to the Contacts table content Uri final Uri uri = Uri.withAppendedPath(Contacts.CONTENT_URI, String.valueOf(data.getLong(ContactsQuery.ID))); mOnContactSelectedListener.onContactSelected(uri); getListView().setItemChecked(mPreviouslySelectedSearchItem, true); } else { // No results, clear selection. onSelectionCleared(); } // Only restore from saved state one time. Next time fall back // to selecting first item. If the fragment state is saved again // then the currently selected item will once again be saved. mPreviouslySelectedSearchItem = 0; mSearchQueryChanged = false; } // Populate itemsMap and pass to service }
From source file:cx.ring.client.HomeActivity.java
@Override public void onTextContact(final CallContact c) { if (c.getPhones().size() > 1) { final CharSequence numbers[] = new CharSequence[c.getPhones().size()]; int i = 0; for (CallContact.Phone p : c.getPhones()) numbers[i++] = p.getNumber().getRawUriString(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.choose_number); builder.setItems(numbers, new DialogInterface.OnClickListener() { @Override//from w w w .j a v a 2s . co m public void onClick(DialogInterface dialog, int which) { CharSequence selected = numbers[which]; Intent intent = new Intent(Intent.ACTION_VIEW) .setClass(HomeActivity.this, ConversationActivity.class) .setData(Uri.withAppendedPath(ConversationActivity.CONTENT_URI, c.getIds().get(0))) .putExtra("number", selected); startActivityForResult(intent, HomeActivity.REQUEST_CODE_CONVERSATION); } }); builder.show(); } else { Intent intent = new Intent(Intent.ACTION_VIEW).setClass(this, ConversationActivity.class) .setData(Uri.withAppendedPath(ConversationActivity.CONTENT_URI, c.getIds().get(0))); startActivityForResult(intent, HomeActivity.REQUEST_CODE_CONVERSATION); } }
From source file:cz.maresmar.sfm.view.MainActivity.java
@NonNull @Override//from w w w . ja va2 s .c o m public Loader<Cursor> onCreateLoader(int id, @Nullable Bundle args) { switch (id) { case USER_LOADER_ID: return new CursorLoader(this, ProviderContract.User.getUri(), new String[] { ProviderContract.User._ID, ProviderContract.User.NAME, ProviderContract.User.PICTURE }, null, null, null); case PORTAL_LOADER_ID: return new CursorLoader(this, ProviderContract.Portal.getUserUri(mSelectedUserId), new String[] { ProviderContract.Portal._ID, ProviderContract.Portal.NAME, ProviderContract.Portal.CREDIT, }, null, null, null); case CREDENTIAL_LOADER_ID: return new CursorLoader(this, ProviderContract.Credentials.getUserUri(mSelectedUserId), new String[] { ProviderContract.Credentials._ID, ProviderContract.Credentials.CREDIT }, null, null, null); case EDIT_ACTIONS_COUNT_LOADER_ID: Uri actionUri = Uri.withAppendedPath(getUserUri(), ProviderContract.ACTION_PATH); return new CursorLoader(this, actionUri, new String[] { "COUNT(" + ProviderContract.Action._ID + ")" }, ProviderContract.Action.SYNC_STATUS + " = " + ProviderContract.ACTION_SYNC_STATUS_EDIT, null, null); default: throw new UnsupportedOperationException("Unknown loader id: " + id); } }
From source file:com.android.email.activity.MessageView.java
/** * Handle clicks on sender, which shows {@link QuickContact} or prompts to add * the sender as a contact.//w w w . j av a 2s. c om */ private void onClickSender() { // Bail early if message or sender not present if (mMessage == null) return; final Address senderEmail = Address.unpackFirst(mMessage.mFrom); if (senderEmail == null) return; // First perform lookup query to find existing contact final ContentResolver resolver = getContentResolver(); final String address = senderEmail.getAddress(); final Uri dataUri = Uri.withAppendedPath(CommonDataKinds.Email.CONTENT_FILTER_URI, Uri.encode(address)); final Uri lookupUri = ContactsContract.Data.getContactLookupUri(resolver, dataUri); if (lookupUri != null) { // Found matching contact, trigger QuickContact QuickContact.showQuickContact(this, mSenderPresenceView, lookupUri, QuickContact.MODE_LARGE, null); } else { // No matching contact, ask user to create one final Uri mailUri = Uri.fromParts("mailto", address, null); final Intent intent = new Intent(ContactsContract.Intents.SHOW_OR_CREATE_CONTACT, mailUri); // Pass along full E-mail string for possible create dialog intent.putExtra(ContactsContract.Intents.EXTRA_CREATE_DESCRIPTION, senderEmail.toString()); // Only provide personal name hint if we have one final String senderPersonal = senderEmail.getPersonal(); if (!TextUtils.isEmpty(senderPersonal)) { intent.putExtra(ContactsContract.Intents.Insert.NAME, senderPersonal); } intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); startActivity(intent); } }
From source file:org.opendatakit.services.forms.provider.FormsProvider.java
/** * This method removes the entry from the content provider, and also removes * any associated files. files: form.xml, [formmd5].formdef, formname * {directory}/*from w w w. j a v a2 s.c om*/ */ @Override public synchronized int delete(@NonNull Uri uri, String where, String[] whereArgs) { possiblyWaitForContentProviderDebugger(); List<String> segments = uri.getPathSegments(); PatchedFilter pf = extractUriFeatures(uri, segments, where, whereArgs); WebLoggerIf logger = WebLogger.getLogger(pf.appName); String[] projection = { FormsColumns._ID, FormsColumns.TABLE_ID, FormsColumns.FORM_ID }; HashMap<String, FormSpec> directories = new HashMap<String, FormSpec>(); DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .generateInternalUseDbHandle(); OdkConnectionInterface db = null; Cursor c = null; Integer idValue = null; String tableIdValue = null; String formIdValue = null; try { // Get the database and run the query // +1 referenceCount if db is returned (non-null) db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(pf.appName, dbHandleName); db.beginTransactionNonExclusive(); c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, pf.whereId, pf.whereIdArgs, null, null, null, null); if (c == null) { throw new SQLException("FAILED Delete into " + uri + " -- unable to query for existing records"); } int idxId = c.getColumnIndex(FormsColumns._ID); int idxTableId = c.getColumnIndex(FormsColumns.TABLE_ID); int idxFormId = c.getColumnIndex(FormsColumns.FORM_ID); if (c.moveToFirst()) { do { idValue = CursorUtils.getIndexAsType(c, Integer.class, idxId); tableIdValue = CursorUtils.getIndexAsString(c, idxTableId); formIdValue = CursorUtils.getIndexAsString(c, idxFormId); FormSpec formSpec = new FormSpec(); formSpec.tableId = tableIdValue; formSpec.formId = formIdValue; formSpec.success = false; directories.put(idValue.toString(), formSpec); } while (c.moveToNext()); } c.close(); c = null; // and now go through this list moving the directories // into the pending-deletion location and deleting them. for (Entry<String, FormSpec> de : directories.entrySet()) { String id = de.getKey(); FormSpec fs = de.getValue(); File srcDir = new File(ODKFileUtils.getFormFolder(pf.appName, fs.tableId, fs.formId)); File destDir = new File(ODKFileUtils.getPendingDeletionTablesFolder(pf.appName), fs.tableId + "." + fs.formId + "." + System.currentTimeMillis()); try { FileUtils.moveDirectory(srcDir, destDir); if (db.delete(DatabaseConstants.FORMS_TABLE_NAME, FormsColumns._ID + "=?", new String[] { id }) > 0) { fs.success = true; } } catch (IOException e) { logger.e(t, "Unable to move directory prior to deleting it: " + e.toString()); logger.printStackTrace(e); } } // commit the transaction... db.setTransactionSuccessful(); } catch (Exception e) { logger.w(t, "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString()); if (e instanceof SQLException) { throw (SQLException) e; } else { throw new SQLException( "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString()); } } finally { if (db != null) { try { try { if (c != null && !c.isClosed()) { c.close(); } } finally { if (db.inTransaction()) { db.endTransaction(); } } } finally { try { db.releaseReference(); } finally { // this closes the connection OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .removeConnection(pf.appName, dbHandleName); } } } } // and now, go through all the files in the pending-deletion // directory and try to release them. File destFolder = new File(ODKFileUtils.getPendingDeletionTablesFolder(pf.appName)); File[] delDirs = destFolder.listFiles(); for (File formIdDir : delDirs) { try { FileUtils.deleteDirectory(formIdDir); } catch (IOException e) { logger.e(t, "Unable to remove directory " + e.toString()); logger.printStackTrace(e); } } int failureCount = 0; for (Entry<String, FormSpec> e : directories.entrySet()) { String id = e.getKey(); FormSpec fs = e.getValue(); 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), id); getContext().getContentResolver().notifyChange(idUri, null); } else { ++failureCount; } } getContext().getContentResolver().notifyChange(uri, null); int count = directories.size(); if (failureCount != 0) { throw new SQLiteException( "Unable to delete all forms (" + (count - failureCount) + " of " + count + " deleted)"); } return count; }
From source file:android.com.example.contactslist.ui.ContactDetailFragment.java
/** * Decodes and returns the contact's thumbnail image. * @param contactUri The Uri of the contact containing the image. * @param imageSize The desired target width and height of the output image in pixels. * @return If a thumbnail image exists for the contact, a Bitmap image, otherwise null. *///from w w w. j a va 2 s . com @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private Bitmap loadContactPhoto(Uri contactUri, 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 a ContentResolver for retrieving the Uri of the image final ContentResolver contentResolver = getActivity().getContentResolver(); // Instantiates an AssetFileDescriptor. Given a content Uri pointing to an image file, the // ContentResolver can return an AssetFileDescriptor for the file. AssetFileDescriptor afd = null; if (Utils.hasICS()) { // On platforms running Android 4.0 (API version 14) and later, a high resolution image // is available from Photo.DISPLAY_PHOTO. try { // Constructs the content Uri for the image Uri displayImageUri = Uri.withAppendedPath(contactUri, Photo.DISPLAY_PHOTO); // Retrieves an AssetFileDescriptor from the Contacts Provider, using the // constructed Uri afd = contentResolver.openAssetFileDescriptor(displayImageUri, "r"); // If the file exists if (afd != null) { // Reads and decodes the file to a Bitmap and scales it to the desired size return ImageLoader.decodeSampledBitmapFromDescriptor(afd.getFileDescriptor(), imageSize, imageSize); } } catch (FileNotFoundException e) { // Catches file not found exceptions if (BuildConfig.DEBUG) { // Log debug message, this is not an error message as this exception is thrown // when a contact is legitimately missing a contact photo (which will be quite // frequently in a long contacts list). Log.d(TAG, "Contact photo not found for contact " + contactUri.toString() + ": " + e.toString()); } } finally { // Once the decode is complete, this closes the file. You must do this each time // you access an AssetFileDescriptor; otherwise, every image load you do will open // a new descriptor. 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 platform version is less than Android 4.0 (API Level 14), use the only available // image URI, which points to a normal-sized image. try { // Constructs the image Uri from the contact Uri and the directory twig from the // Contacts.Photo table Uri imageUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY); // Retrieves an AssetFileDescriptor from the Contacts Provider, using the constructed // Uri afd = getActivity().getContentResolver().openAssetFileDescriptor(imageUri, "r"); // If the file exists if (afd != null) { // Reads the image from the file, decodes it, and scales it to the available screen // area return ImageLoader.decodeSampledBitmapFromDescriptor(afd.getFileDescriptor(), imageSize, imageSize); } } catch (FileNotFoundException e) { // Catches file not found exceptions if (BuildConfig.DEBUG) { // Log debug message, this is not an error message as this exception is thrown // when a contact is legitimately missing a contact photo (which will be quite // frequently in a long contacts list). Log.d(TAG, "Contact photo not found for contact " + contactUri.toString() + ": " + e.toString()); } } finally { // Once the decode is complete, this closes the file. You must do this each time you // access an AssetFileDescriptor; otherwise, every image load you do will open a new // descriptor. if (afd != null) { try { afd.close(); } catch (IOException e) { // Closing a file descriptor might cause an IOException if the file is // already closed. Ignore this. } } } // If none of the case selectors match, returns null. return null; }
From source file:com.zegoggles.smssync.CursorToMessage.java
private List<BodyPart> getBodyParts(final Uri uriPart) throws MessagingException { final List<BodyPart> parts = new ArrayList<BodyPart>(); Cursor curPart = mContext.getContentResolver().query(uriPart, null, null, null, null); // _id, mid, seq, ct, name, chset, cd, fn, cid, cl, ctt_s, ctt_t, _data, text while (curPart != null && curPart.moveToNext()) { final String id = curPart.getString(curPart.getColumnIndex("_id")); final String contentType = curPart.getString(curPart.getColumnIndex("ct")); final String fileName = curPart.getString(curPart.getColumnIndex("cl")); final String text = curPart.getString(curPart.getColumnIndex("text")); if (LOCAL_LOGV) Log.v(TAG, String.format("processing part %s, name=%s (%s)", id, fileName, contentType)); if (contentType.startsWith("text/") && !TextUtils.isEmpty(text)) { // text parts.add(new MimeBodyPart(new TextBody(text), contentType)); } else if (contentType.equalsIgnoreCase("application/smil")) { // silently ignore SMIL stuff } else {//w ww .j av a2 s . com // attach everything else final Uri partUri = Uri.withAppendedPath(ServiceBase.MMS_PROVIDER, "part/" + id); BodyPart part = new MimeBodyPart(new MmsAttachmentBody(partUri, mContext), contentType); part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, String.format("%s;\n name=\"%s\"", contentType, fileName != null ? fileName : "attachment")); part.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64"); part.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION, "attachment"); parts.add(part); } } if (curPart != null) curPart.close(); return parts; }
From source file:miguelmaciel.play.anonymouscall.ui.ContactsListFragment.java
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // This swaps the new cursor into the adapter. if (loader.getId() == ContactsQuery.QUERY_ID) { mAdapter.swapCursor(data);//from w w w .ja v a 2 s.c o m // If this is a two-pane layout and there is a search query then // there is some additional work to do around default selected // search item. if (mIsTwoPaneLayout && !TextUtils.isEmpty(mSearchTerm) && mSearchQueryChanged) { // Selects the first item in results, unless this fragment has // been restored from a saved state (like orientation change) // in which case it selects the previously selected search item. if (data != null && data.moveToPosition(mPreviouslySelectedSearchItem)) { // Creates the content Uri for the previously selected contact by appending the // contact's ID to the Contacts table content Uri final Uri uri = Uri.withAppendedPath(Contacts.CONTENT_URI, String.valueOf(data.getLong(ContactsQuery.ID))); mOnContactSelectedListener.onContactSelected(uri); getListView().setItemChecked(mPreviouslySelectedSearchItem, true); } else { // No results, clear selection. onSelectionCleared(); } // Only restore from saved state one time. Next time fall back // to selecting first item. If the fragment state is saved again // then the currently selected item will once again be saved. mPreviouslySelectedSearchItem = 0; mSearchQueryChanged = false; } //This method will get all Names and respective phone numbers to an array [arrID/arrPhones] if (data.getCount() > 0) { //Clear the arrays arrID.clear(); arrPhones.clear(); //Go to first position of the array and start getting the data data.moveToFirst(); do { String contactId = data.getString(data.getColumnIndex(Contacts._ID)); // // Get all phone numbers. // Cursor phones = null; try { phones = getActivity().getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null); if (phones.getCount() > 0) { phones.moveToFirst(); do { String number = phones.getString( phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); int type = phones .getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE)); switch (type) { case ContactsContract.CommonDataKinds.Phone.TYPE_HOME: // do something with the Home number here... arrID.add(contactId); arrPhones.add(number); break; case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE: // do something with the Mobile number here... arrID.add(contactId); arrPhones.add(number); break; case ContactsContract.CommonDataKinds.Phone.TYPE_WORK: // do something with the Work number here... arrID.add(contactId); arrPhones.add(number); break; } } while (phones.moveToNext()); // phones.close(); } } catch (Throwable e) { phones.close(); } finally { phones.close(); } } while (data.moveToNext()); } } }
From source file:com.fvd.nimbus.MainActivity.java
String getImagePath() { String[] projection = { MediaStore.Images.Thumbnails._ID, // The columns we want MediaStore.Images.Thumbnails.IMAGE_ID, MediaStore.Images.Thumbnails.KIND, MediaStore.Images.Thumbnails.DATA }; String selection = MediaStore.Images.Thumbnails.KIND + "=" + // Select only mini's MediaStore.Images.Thumbnails.MINI_KIND; String sort = MediaStore.Images.Thumbnails._ID + " DESC"; //At the moment, this is a bit of a hack, as I'm returning ALL images, and just taking the latest one. There is a better way to narrow this down I think with a WHERE clause which is currently the selection variable Cursor myCursor = this.managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, selection, null, sort);/*ww w . ja va 2 s . c o m*/ long imageId = 0l; long thumbnailImageId = 0l; String thumbnailPath = ""; try { myCursor.moveToFirst(); imageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID)); thumbnailImageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID)); thumbnailPath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA)); } finally { myCursor.close(); } //Create new Cursor to obtain the file Path for the large image String[] largeFileProjection = { MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA }; String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC"; myCursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort); String largeImagePath = ""; try { myCursor.moveToFirst(); largeImagePath = myCursor .getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA)); } finally { myCursor.close(); } // These are the two URI's you'll be interested in. They give you a handle to the actual images Uri uriLargeImage = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(imageId)); Uri uriThumbnailImage = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, String.valueOf(thumbnailImageId)); if (largeImagePath.length() > 0) return largeImagePath; else if (uriLargeImage != null) return uriLargeImage.getPath(); else if (uriThumbnailImage != null) return uriThumbnailImage.getPath(); else return ""; }