List of usage examples for android.net Uri withAppendedPath
public static Uri withAppendedPath(Uri baseUri, String pathSegment)
From source file:fr.jbteam.jabboid.core.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 v a 2 s. co 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:android.com.example.contactslist.ui.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 ww .j a v a 2 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.ichi2.anki.tests.ContentProviderTest.java
/** * Test query to specific deck ID/*from w w w .jav a 2 s. c o m*/ * @throws Exception */ public void testQueryCertainDeck() throws Exception { Collection col; col = CollectionHelper.getInstance().getCol(getContext()); long deckId = mTestDeckIds[0]; Uri deckUri = Uri.withAppendedPath(FlashCardsContract.Deck.CONTENT_ALL_URI, Long.toString(deckId)); Cursor decksCursor = getContext().getContentResolver().query(deckUri, null, null, null, null); try { if (decksCursor == null || !decksCursor.moveToFirst()) { fail("No deck received. Should have delivered deck with id " + deckId); } else { long returnedDeckID = decksCursor .getLong(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_ID)); String returnedDeckName = decksCursor .getString(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_NAME)); JSONObject realDeck = col.getDecks().get(deckId); assertEquals("Check that received deck ID equals real deck ID", deckId, returnedDeckID); assertEquals("Check that received deck name equals real deck name", realDeck.getString("name"), returnedDeckName); } } finally { decksCursor.close(); } }
From source file:com.owncloud.android.datamodel.FileDataStorageManager.java
private boolean removeFolderInDb(OCFile folder) { Uri folder_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, "" + folder.getFileId()); // URI for recursive deletion String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + ProviderTableMeta.FILE_PATH + "=?"; String[] whereArgs = new String[] { mAccount.name, folder.getRemotePath() }; int deleted = 0; if (getContentProviderClient() != null) { try {/*from ww w.jav a2s. c o m*/ deleted = getContentProviderClient().delete(folder_uri, where, whereArgs); } catch (RemoteException e) { e.printStackTrace(); } } else { deleted = getContentResolver().delete(folder_uri, where, whereArgs); } return deleted > 0; }
From source file:com.phonegap.ContactAccessorSdk3_4.java
/** * Takes a JSON contact object and loops through the available phone numbers. If the phone * number has an id that is not equal to null the phone number will be updated in the database. * If the id is null then we treat it as a new phone number. * /* w w w .j a v a2s . c o m*/ * @param contact the contact to extract the phone numbers from * @param uri the base URI for this contact. */ private void savePhoneNumbers(JSONObject contact, Uri uri) { ContentValues values = new ContentValues(); Uri phonesUri = Uri.withAppendedPath(uri, Contacts.People.Phones.CONTENT_DIRECTORY); String id = null; try { JSONArray phones = contact.getJSONArray("phoneNumbers"); if (phones != null && phones.length() > 0) { JSONObject phone; for (int i = 0; i < phones.length(); i++) { phone = phones.getJSONObject(i); id = getJsonString(phone, "id"); values.put(Contacts.Phones.NUMBER, getJsonString(phone, "value")); values.put(Contacts.Phones.TYPE, getPhoneType(getJsonString(phone, "type"))); if (id == null) { Uri phoneUpdate = mApp.getContentResolver().insert(phonesUri, values); } else { Uri newUri = Uri.withAppendedPath(phonesUri, id); mApp.getContentResolver().update(newUri, values, null, null); } } } } catch (JSONException e) { Log.d(LOG_TAG, "Could not save phones = " + e.getMessage()); } }
From source file:br.com.mybaby.contatos.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 v a 2 s . c om * * @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 (Util.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:nl.sogeti.android.gpstracker.viewer.LoggerMap.java
/** * Retrieve the last point of the current track *///from w ww .j av a 2 s . c om private GeoPoint getLastTrackPoint() { Cursor waypoint = null; GeoPoint lastPoint = null; // First try the service which might have a cached version Location lastLoc = mLoggerServiceManager.getLastWaypoint(); if (lastLoc != null) { int microLatitude = (int) (lastLoc.getLatitude() * 1E6d); int microLongitude = (int) (lastLoc.getLongitude() * 1E6d); lastPoint = new GeoPoint(microLatitude, microLongitude); } // If nothing yet, try the content resolver and query the track if (lastPoint == null || lastPoint.getLatitudeE6() == 0 || lastPoint.getLongitudeE6() == 0) { try { ContentResolver resolver = this.getContentResolver(); waypoint = resolver.query(Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/waypoints"), new String[] { Waypoints.LATITUDE, Waypoints.LONGITUDE, "max(" + Waypoints.TABLE + "." + Waypoints._ID + ")" }, null, null, null); if (waypoint != null && waypoint.moveToLast()) { int microLatitude = (int) (waypoint.getDouble(0) * 1E6d); int microLongitude = (int) (waypoint.getDouble(1) * 1E6d); lastPoint = new GeoPoint(microLatitude, microLongitude); } } finally { if (waypoint != null) { waypoint.close(); } } } // If nothing yet, try the last generally known location if (lastPoint == null || lastPoint.getLatitudeE6() == 0 || lastPoint.getLongitudeE6() == 0) { lastPoint = getLastKnowGeopointLocation(); } return lastPoint; }
From source file:org.opendatakit.survey.activities.MainMenuActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // android.os.Debug.waitForDebugger(); submenuPage = getIntentExtras().getString("_sync_state"); try {/* w w w.j a va 2 s . c om*/ // ensure that we have a BackgroundTaskFragment... // create it programmatically because if we place it in the // layout XML, it will be recreated with each screen rotation // and we don't want that!!! mPropertyManager = new PropertyManager(this); // must be at the beginning of any activity that can be called from an // external intent setAppName(ODKFileUtils.getOdkDefaultAppName()); Uri uri = getIntent().getData(); Uri formUri = null; if (uri != null) { // initialize to the URI, then we will customize further based upon the // savedInstanceState... final Uri uriFormsProvider = FormsProviderAPI.CONTENT_URI; final Uri uriWebView = UrlUtils.getWebViewContentUri(this); if (uri.getScheme().equalsIgnoreCase(uriFormsProvider.getScheme()) && uri.getAuthority().equalsIgnoreCase(uriFormsProvider.getAuthority())) { List<String> segments = uri.getPathSegments(); if (segments != null && segments.size() == 1) { String appName = segments.get(0); setAppName(appName); } else if (segments != null && segments.size() >= 2) { String appName = segments.get(0); setAppName(appName); String tableId = segments.get(1); String formId = (segments.size() > 2) ? segments.get(2) : null; formUri = Uri.withAppendedPath(Uri.withAppendedPath( Uri.withAppendedPath(FormsProviderAPI.CONTENT_URI, appName), tableId), formId); } else { createErrorDialog(getString(R.string.invalid_uri_expecting_n_segments, uri.toString(), 2), EXIT); return; } } else if (uri.getScheme().equals(uriWebView.getScheme()) && uri.getAuthority().equals(uriWebView.getAuthority()) && uri.getPort() == uriWebView.getPort()) { List<String> segments = uri.getPathSegments(); if (segments != null && segments.size() == 1) { String appName = segments.get(0); setAppName(appName); } else { createErrorDialog(getString(R.string.invalid_uri_expecting_one_segment, uri.toString()), EXIT); return; } } else { createErrorDialog(getString(R.string.unrecognized_uri, uri.toString(), uriWebView.toString(), uriFormsProvider.toString()), EXIT); return; } } if (savedInstanceState != null) { // if appName is explicitly set, use it... setAppName(savedInstanceState.containsKey(IntentConsts.INTENT_KEY_APP_NAME) ? savedInstanceState.getString(IntentConsts.INTENT_KEY_APP_NAME) : getAppName()); if (savedInstanceState.containsKey(CONFLICT_TABLES)) { mConflictTables = savedInstanceState.getBundle(CONFLICT_TABLES); } } try { String appName = getAppName(); if (appName != null && appName.length() != 0) { ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); } } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); return; } WebLogger.getLogger(getAppName()).i(t, "Starting up, creating directories"); if (savedInstanceState != null) { // if we are restoring, assume that initialization has already occurred. dispatchStringWaitingForData = savedInstanceState.containsKey(DISPATCH_STRING_WAITING_FOR_DATA) ? savedInstanceState.getString(DISPATCH_STRING_WAITING_FOR_DATA) : null; actionWaitingForData = savedInstanceState.containsKey(ACTION_WAITING_FOR_DATA) ? savedInstanceState.getString(ACTION_WAITING_FOR_DATA) : null; currentFragment = ScreenList.valueOf(savedInstanceState.containsKey(CURRENT_FRAGMENT) ? savedInstanceState.getString(CURRENT_FRAGMENT) : currentFragment.name()); if (savedInstanceState.containsKey(FORM_URI)) { FormIdStruct newForm = FormIdStruct.retrieveFormIdStruct(getContentResolver(), Uri.parse(savedInstanceState.getString(FORM_URI))); if (newForm != null) { setAppName(newForm.appName); setCurrentForm(newForm); } } setInstanceId( savedInstanceState.containsKey(INSTANCE_ID) ? savedInstanceState.getString(INSTANCE_ID) : getInstanceId()); setUploadTableId(savedInstanceState.containsKey(UPLOAD_TABLE_ID) ? savedInstanceState.getString(UPLOAD_TABLE_ID) : getUploadTableId()); String tmpScreenPath = savedInstanceState.containsKey(SCREEN_PATH) ? savedInstanceState.getString(SCREEN_PATH) : getScreenPath(); String tmpControllerState = savedInstanceState.containsKey(CONTROLLER_STATE) ? savedInstanceState.getString(CONTROLLER_STATE) : getControllerState(); setSectionScreenState(tmpScreenPath, tmpControllerState); setAuxillaryHash(savedInstanceState.containsKey(AUXILLARY_HASH) ? savedInstanceState.getString(AUXILLARY_HASH) : getAuxillaryHash()); if (savedInstanceState.containsKey(SESSION_VARIABLES)) { sessionVariables = savedInstanceState.getBundle(SESSION_VARIABLES); } if (savedInstanceState.containsKey(SECTION_STATE_SCREEN_HISTORY)) { sectionStateScreenHistory = savedInstanceState .getParcelableArrayList(SECTION_STATE_SCREEN_HISTORY); } if (savedInstanceState.containsKey(QUEUED_ACTIONS)) { String[] actionOutcomesArray = savedInstanceState.getStringArray(QUEUED_ACTIONS); queuedActions.clear(); queuedActions.addAll(Arrays.asList(actionOutcomesArray)); } if (savedInstanceState != null && savedInstanceState.containsKey(RESPONSE_JSON)) { String[] pendingResponseJSON = savedInstanceState.getStringArray(RESPONSE_JSON); queueResponseJSON.addAll(Arrays.asList(pendingResponseJSON)); } } else if (formUri != null) { // request specifies a specific formUri -- try to open that FormIdStruct newForm = FormIdStruct.retrieveFormIdStruct(getContentResolver(), formUri); if (newForm == null) { // can't find it -- launch the initialization dialog to hopefully // discover it. WebLogger.getLogger(getAppName()).i(t, "onCreate -- calling setRunInitializationTask"); ((Survey) getApplication()).setRunInitializationTask(getAppName()); currentFragment = ScreenList.WEBKIT; } else { transitionToFormHelper(uri, newForm); } } } catch (Exception e) { createErrorDialog(e.getMessage(), EXIT); } finally { setContentView(R.layout.main_screen); ActionBar actionBar = getActionBar(); actionBar.show(); } }
From source file:edu.umbc.cs.ebiquity.mithril.parserapp.contentparsers.contacts.ContactsListFragment.java
@Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // If this is the loader for finding contacts in the Contacts Provider // (the only one supported) if (id == ContactsQuery.QUERY_ID) { // There are two types of searches, one which displays all contacts and // one which filters contacts by a search query. If mSearchTerm is set // then a search query has been entered and the latter should be used. if (mSearchTerm == null) { // Since there's no search string, use the content URI that searches the entire // Contacts table setContentUri(ContactsQuery.CONTENT_URI); } else {//from w ww. ja v a2 s .co m // Since there's a search string, use the special content Uri that searches the // Contacts table. The URI consists of a base Uri and the search string. setContentUri(Uri.withAppendedPath(ContactsQuery.FILTER_URI, Uri.encode(mSearchTerm))); } // if(ParserApplication.isContactsAccessPolicyAllowed()){ // Returns a new CursorLoader for querying the Contacts table. No arguments are used // for the selection clause. The search string is either encoded onto the content URI, // or no contacts search string is used. The other search criteria are constants. See // the ContactsQuery interface. return new CursorLoader(getActivity(), getContentUri(), ContactsQuery.PROJECTION, ContactsQuery.SELECTION, null, ContactsQuery.SORT_ORDER); // } // else { // /** // * If you return null here then the access to the content is actually blocked! // */ // return null; // } } // Log.e(TAG, "onCreateLoader - incorrect ID provided (" + id + ")"); return null; }
From source file:org.opendatakit.survey.android.activities.MainMenuActivity.java
@Override public FrameworkFormPathInfo getFrameworkFormPathInfo() { // Find the formPath for the default form with the most recent // version... Cursor c = null;/*from w w w.jav a 2s .com*/ String formPath = null; Long lastModified = null; try { // // the default form is named 'default' ... String selection = FormsColumns.FORM_ID + "=?"; String[] selectionArgs = { FormsColumns.COMMON_BASE_FORM_ID }; // use the most recently created of the matches // (in case DB corrupted) String orderBy = FormsColumns.FORM_VERSION + " DESC"; c = getContentResolver().query(Uri.withAppendedPath(FormsProviderAPI.CONTENT_URI, appName), null, selection, selectionArgs, orderBy); if (c != null && c.getCount() > 0) { // we found a match... c.moveToFirst(); formPath = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_PATH)); lastModified = ODKDatabaseUtils.get().getIndexAsType(c, Long.class, c.getColumnIndex(FormsColumns.DATE)); } } finally { if (c != null && !c.isClosed()) { c.close(); } } if (formPath == null) { return null; } else { return new FrameworkFormPathInfo(formPath, lastModified); } }