List of usage examples for android.net Uri withAppendedPath
public static Uri withAppendedPath(Uri baseUri, String pathSegment)
From source file:com.visva.voicerecorder.view.fragments.FragmentContact.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. j a 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); mListContact.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; } } }
From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java
/** * This method removes the entry from the content provider, and also removes * any associated files. files: form.xml, [formmd5].formdef, formname * {directory}/* www. j ava 2 s . co m*/ */ @Override public int delete(Uri uri, String where, String[] whereArgs) { List<String> segments = uri.getPathSegments(); if (segments.size() < 1 || segments.size() > 2) { throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri); } String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); WebLogger log = WebLogger.getLogger(appName); String uriFormId = ((segments.size() == 2) ? segments.get(1) : null); boolean isNumericId = StringUtils.isNumeric(uriFormId); // Modify the where clause to account for the presence of // a form id. Accept either: // (1) numeric _ID value // (2) string FORM_ID value. String whereId; String[] whereIdArgs; if (uriFormId == null) { whereId = where; whereIdArgs = whereArgs; } else { if (TextUtils.isEmpty(where)) { whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?"; whereIdArgs = new String[1]; whereIdArgs[0] = uriFormId; } else { whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")"; whereIdArgs = new String[whereArgs.length + 1]; whereIdArgs[0] = uriFormId; for (int i = 0; i < whereArgs.length; ++i) { whereIdArgs[i + 1] = whereArgs[i]; } } } Cursor del = null; Integer idValue = null; String tableIdValue = null; String formIdValue = null; HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>(); try { del = this.query(uri, null, whereId, whereIdArgs, null); if (del == null) { throw new SQLException("FAILED Delete into " + uri + " -- unable to query for existing records"); } del.moveToPosition(-1); while (del.moveToNext()) { idValue = ODKDatabaseUtils.get().getIndexAsType(del, Integer.class, del.getColumnIndex(FormsColumns._ID)); tableIdValue = ODKDatabaseUtils.get().getIndexAsString(del, del.getColumnIndex(FormsColumns.TABLE_ID)); formIdValue = ODKDatabaseUtils.get().getIndexAsString(del, del.getColumnIndex(FormsColumns.FORM_ID)); File mediaDir = ODKFileUtils.asAppFile(appName, ODKDatabaseUtils.get().getIndexAsString(del, del.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH))); mediaDirs.put(mediaDir, (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS); } } catch (Exception e) { log.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 (del != null && !del.isClosed()) { del.close(); } } SQLiteDatabase db = null; int count; try { db = DatabaseFactory.get().getDatabase(getContext(), appName); db.beginTransaction(); count = db.delete(DatabaseConstants.FORMS_TABLE_NAME, whereId, whereIdArgs); db.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); log.w(t, "Unable to perform deletion " + e.toString()); return 0; } finally { if (db != null) { db.endTransaction(); db.close(); } } // and attempt to move these directories to the stale forms location // so that they do not immediately get rescanned... for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) { try { moveDirectory(appName, entry.getValue(), entry.getKey()); } catch (IOException e) { e.printStackTrace(); log.e(t, "Unable to move directory " + e.toString()); } } if (count == 1) { Uri formUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), formIdValue); getContext().getContentResolver().notifyChange(formUri, null); Uri idUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), Long.toString(idValue)); getContext().getContentResolver().notifyChange(idUri, null); } else { getContext().getContentResolver().notifyChange(uri, null); } return count; }
From source file:com.nononsenseapps.feeder.ui.FeedFragment.java
@Override public Loader onCreateLoader(final int ID, final Bundle bundle) { if (ID == FEEDITEMS_LOADER) { return new FeedItemDeltaCursorLoader(getActivity(), FeedItemSQL.URI_FEED_ITEMS.buildUpon() .appendQueryParameter(RssContentProvider.QUERY_PARAM_LIMIT, "50").build(), FeedItemSQL.FIELDS, getLoaderSelection(), getLoaderSelectionArgs(), FeedItemSQL.COL_PUBDATE + " DESC"); } else if (ID == FEED_LOADER) { return new CursorLoader(getActivity(), Uri.withAppendedPath(FeedSQL.URI_FEEDS, Long.toString(id)), FeedSQL.FIELDS, null, null, null); } else if (ID == FEED_SETTINGS_LOADER) { String where;//from w ww . j a va 2s.c o m String[] whereArgs; if (id > 0) { where = Util.WHEREIDIS; whereArgs = Util.LongsToStringArray(id); } else { where = FeedSQL.COL_TAG + " IS ?"; whereArgs = Util.ToStringArray(tag); } return new CursorLoader(getActivity(), FeedSQL.URI_FEEDS, Util.ToStringArray("DISTINCT " + FeedSQL.COL_NOTIFY), where, whereArgs, null); } return null; }
From source file:learn2crack.activities.WnContactsListFragment.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.// w w w . j a v a2 s . com * * @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) { } 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.radar.niyo.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) { Uri contentUri;//from ww w . ja v a 2 s . c o m // 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 // contentUri = ContactsQuery.CONTENT_URI; // } else { // // 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. // contentUri = // Uri.withAppendedPath(ContactsQuery.FILTER_URI, Uri.encode(mSearchTerm)); // } if (mSearchTerm != null) { contentUri = Uri.withAppendedPath(CommonDataKinds.Email.CONTENT_FILTER_URI, Uri.encode(mSearchTerm)); } else { contentUri = CommonDataKinds.Email.CONTENT_URI; } // 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(), contentUri, ContactsQuery.PROJECTION, ContactsQuery.SELECTION, null, ContactsQuery.SORT_ORDER); } Log.e(TAG, "onCreateLoader - incorrect ID provided (" + id + ")"); return null; }
From source file:com.ichi2.anki.tests.ContentProviderTest.java
/** * Check that querying the current model gives a valid result *//* w w w . ja v a2s . com*/ public void testQueryCurrentModel() { final ContentResolver cr = getContext().getContentResolver(); Uri uri = Uri.withAppendedPath(FlashCardsContract.Model.CONTENT_URI, FlashCardsContract.Model.CURRENT_MODEL_ID); final Cursor modelCursor = cr.query(uri, null, null, null, null); assertNotNull(modelCursor); try { assertEquals("Check that there is exactly one result", 1, modelCursor.getCount()); assertTrue("Move to beginning of cursor", modelCursor.moveToFirst()); assertNotNull("Check non-empty field names", modelCursor.getString(modelCursor.getColumnIndex(FlashCardsContract.Model.FIELD_NAMES))); assertTrue("Check at least one template", modelCursor.getInt(modelCursor.getColumnIndex(FlashCardsContract.Model.NUM_CARDS)) > 0); } finally { modelCursor.close(); } }
From source file:group.pals.android.lib.ui.filechooser.utils.ui.bookmark.BookmarkFragment.java
/** * Shows a dialog to let user enter new name or change current name of a * bookmark./*w w w . j a v a2s .c om*/ * * @param context * {@link Context} * @param providerId * the provider ID. * @param id * the bookmark ID. * @param uri * the URI to the bookmark. * @param name * the name. To enter new name, this is the suggested name you * provide. To rename, this is the old name. */ public static void doEnterNewNameOrRenameBookmark(final Context context, final String providerId, final int id, final Uri uri, final String name) { final AlertDialog dialog = Dlg.newDlg(context); View view = LayoutInflater.from(context).inflate(R.layout.afc_simple_text_input_view, null); final EditText textName = (EditText) view.findViewById(R.id.afc_text1); textName.setText(name); textName.selectAll(); textName.setHint(R.string.afc_hint_new_name); textName.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { Ui.showSoftKeyboard(textName, false); Button btn = dialog.getButton(DialogInterface.BUTTON_POSITIVE); if (btn.isEnabled()) btn.performClick(); return true; } return false; }// onEditorAction() }); dialog.setView(view); dialog.setIcon(R.drawable.afc_bookmarks_dark); dialog.setTitle(id < 0 ? R.string.afc_title_new_bookmark : R.string.afc_title_rename); dialog.setButton(DialogInterface.BUTTON_POSITIVE, context.getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String newName = textName.getText().toString().trim(); if (android.text.TextUtils.isEmpty(newName)) { Dlg.toast(context, R.string.afc_msg_bookmark_name_is_invalid, Dlg._LengthShort); return; } Ui.showSoftKeyboard(textName, false); ContentValues values = new ContentValues(); values.put(BookmarkContract.Bookmark._ColumnName, newName); if (id >= 0) { values.put(BookmarkContract.Bookmark._ColumnModificationTime, DbUtils.formatNumber(new Date().getTime())); context.getContentResolver() .update(Uri.withAppendedPath(BookmarkContract.Bookmark._ContentIdUriBase, Uri.encode(Integer.toString(id))), values, null, null); } else { /* * Check if the URI exists or doesn't. If it exists, * update it instead of inserting the new one. */ Cursor cursor = context.getContentResolver().query( BookmarkContract.Bookmark._ContentUri, null, String.format("%s = %s AND %s LIKE %s", BookmarkContract.Bookmark._ColumnProviderId, DatabaseUtils.sqlEscapeString(providerId), BookmarkContract.Bookmark._ColumnUri, DatabaseUtils.sqlEscapeString(uri.toString())), null, null); try { if (cursor != null && cursor.moveToFirst()) { values.put(BookmarkContract.Bookmark._ColumnModificationTime, DbUtils.formatNumber(new Date().getTime())); context.getContentResolver().update( Uri.withAppendedPath(BookmarkContract.Bookmark._ContentIdUriBase, Uri.encode(cursor.getString( cursor.getColumnIndex(BookmarkContract.Bookmark._ID)))), values, null, null); } else { values.put(BookmarkContract.Bookmark._ColumnProviderId, providerId); values.put(BookmarkContract.Bookmark._ColumnUri, uri.toString()); context.getContentResolver().insert(BookmarkContract.Bookmark._ContentUri, values); } } finally { if (cursor != null) cursor.close(); } } Dlg.toast(context, context.getString(R.string.afc_msg_done), Dlg._LengthShort); }// onClick() }); dialog.show(); Ui.showSoftKeyboard(textName, true); final Button buttonOk = dialog.getButton(DialogInterface.BUTTON_POSITIVE); buttonOk.setEnabled(id < 0); textName.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { String newName = s.toString().trim(); boolean enabled = !android.text.TextUtils.isEmpty(newName); buttonOk.setEnabled(enabled); /* * If renaming, only enable button OK if new name is not equal * to the old one. */ if (enabled && id >= 0) buttonOk.setEnabled(!newName.equals(name)); } }); }
From source file:net.ddns.mlsoftlaberge.contactslist.ui.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) { Uri contentUri;/* w w w. j a va 2s .c o m*/ // 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 contentUri = ContactsQuery.CONTENT_URI; } else { // 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. contentUri = Uri.withAppendedPath(ContactsQuery.FILTER_URI, Uri.encode(mSearchTerm)); } // 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. if (starredfind == 0) { return new CursorLoader(getActivity(), contentUri, ContactsQuery.PROJECTION, ContactsQuery.SELECTION, null, ContactsQuery.SORT_ORDER); } else { return new CursorLoader(getActivity(), contentUri, ContactsQuery.PROJECTION, ContactsQuery.SELECTION2, null, ContactsQuery.SORT_ORDER); } } Log.e(TAG, "onCreateLoader - incorrect ID provided (" + id + ")"); return null; }
From source file:org.simlar.SimlarService.java
void loadContactsFromTelephonebook() { new AsyncTask<Void, Void, Map<String, ContactData>>() { @Override/*w ww. j a va2 s. c o m*/ protected Map<String, ContactData> doInBackground(Void... params) { Log.i(LOGTAG, "loading contacts from telephone book"); Map<String, ContactData> result = new HashMap<String, SimlarService.ContactData>(); final String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.PHOTO_ID }; final Cursor contacts = getContentResolver() .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null); while (contacts.moveToNext()) { final long contactId = contacts.getLong(0); final String number = SimlarNumber.createSimlarNumber(contacts.getString(1)); final String name = contacts.getString(2); final boolean hasPhotoId = contacts.getLong(3) != 0; String photoUri = null; if (Util.isNullOrEmpty(number)) { continue; } if (hasPhotoId) { Uri u = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId); u = Uri.withAppendedPath(u, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY); photoUri = u.toString(); } if (!result.containsKey(number)) { result.put(number, new ContactData(name, ContactStatus.UNKNOWN, photoUri)); Log.d(LOGTAG, "adding contact " + name + " " + number); } } contacts.close(); return result; } @Override protected void onPostExecute(Map<String, ContactData> result) { mContacts = result; requestRegisteredContacts(); } }.execute(); }
From source file:com.hybris.mobile.lib.commerce.sync.CatalogSyncAdapter.java
/** * Save the product by calling the content provider * * @param product Product to be saved * @param categoryIds List of Category Identifier in String format * @param isDetails true if product detail call else false for product with less info *//*from ww w . j a v a2s . c om*/ private void saveProduct(DataSync product, List<String> categoryIds, boolean isDetails) { Log.i(TAG, "Saving the product " + product.getId() + " for category " + categoryIds); // Saving the link product - categories for (String idCategory : categoryIds) { Log.i(TAG, "Saving the link category " + idCategory + " - product" + product.getId()); ContentValues contentValues = new ContentValues(); contentValues.put(CatalogContract.DataBaseDataLinkGroup.ATT_GROUP_ID, idCategory); contentValues.put(CatalogContract.DataBaseDataLinkGroup.ATT_DATA_ID, product.getId()); getContext().getContentResolver().insert( Uri.withAppendedPath(CatalogContract.Provider.getUriGroup(AUTHORITY), product.getId()), contentValues); } // Saving the product ContentValues contentValues = new ContentValues(); contentValues.put(CatalogContract.DataBaseData.ATT_DATA_ID, product.getId()); contentValues.put(CatalogContract.DataBaseData.ATT_DATA, product.getData()); contentValues.put(CatalogContract.DataBaseData.ATT_STATUS, SyncStatus.UPTODATE.getValue()); getContext().getContentResolver().insert( Uri.withAppendedPath(CatalogContract.Provider.getUriData(AUTHORITY), product.getId()), contentValues); if (isDetails) { getContext().getContentResolver().insert( Uri.withAppendedPath(CatalogContract.Provider.getUriDataDetails(AUTHORITY), product.getId()), contentValues); } }