List of usage examples for android.net Uri withAppendedPath
public static Uri withAppendedPath(Uri baseUri, String pathSegment)
From source file:nl.sogeti.android.gpstracker.viewer.LoggerMap.java
/** * For the current track identifier the route of that track is drawn by * adding a OverLay for each segments in the track *///from w ww . j av a2 s .c o m private void createDataOverlays() { mLastSegmentOverlay = null; resetOverlay(); setupHardwareAcceleration(); ContentResolver resolver = this.getContentResolver(); Cursor segments = null; int trackColoringMethod = Integer.valueOf(mSharedPreferences.getString(Constants.TRACKCOLORING, "2")) .intValue(); try { Uri segmentsUri = Uri.withAppendedPath(Tracks.CONTENT_URI, this.mTrackId + "/segments"); segments = resolver.query(segmentsUri, new String[] { Segments._ID }, null, null, null); if (segments != null && segments.moveToFirst()) { do { long segmentsId = segments.getLong(0); Uri segmentUri = ContentUris.withAppendedId(segmentsUri, segmentsId); SegmentOverlay segmentOverlay = new SegmentOverlay(this, segmentUri, trackColoringMethod, mAverageSpeed, this.mMapView, mHandler); mMapView.getOverlays().add(segmentOverlay); mLastSegmentOverlay = segmentOverlay; if (segments.isFirst()) { segmentOverlay.addPlacement(SegmentOverlay.FIRST_SEGMENT); } if (segments.isLast()) { segmentOverlay.addPlacement(SegmentOverlay.LAST_SEGMENT); } mLastSegment = segmentsId; } while (segments.moveToNext()); } } finally { if (segments != null) { segments.close(); } } Uri lastSegmentUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments/" + mLastSegment + "/waypoints"); resolver.unregisterContentObserver(this.mSegmentWaypointsObserver); resolver.registerContentObserver(lastSegmentUri, false, this.mSegmentWaypointsObserver); }
From source file:android.com.example.contactslist.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);// w ww . java 2 s . com // 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; } } }
From source file:com.tavant.droid.womensecurity.fragments.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 ww w. j av a 2 s .c om*/ if (!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; } } }
From source file:fr.jbteam.jabboid.core.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. */// w w w . j a va2 s .c o m @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.example.linhdq.test.documents.viewing.grid.DocumentGridActivity.java
@Override public Loader<Cursor> onCreateLoader(final int documentId, final Bundle bundle) { final Uri uri = Uri.withAppendedPath(DocumentContentProvider.CONTENT_URI, String.valueOf(documentId)); return new CursorLoader(this, uri, new String[] { DocumentContentProvider.Columns.TITLE, DocumentContentProvider.Columns.ID }, null, null, "created ASC"); }
From source file:org.openintents.shopping.ui.ShoppingActivity.java
/** * Called when the activity is first created. *///from w w w .j ava 2 s . com @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); if (debug) { Log.d(TAG, "Shopping list onCreate()"); } mSortOrder = PreferenceActivity.getShoppingListSortOrderFromPrefs(this); mDistribution.setFirst(MENU_DISTRIBUTION_START, DIALOG_DISTRIBUTION_START); // Check whether EULA has been accepted // or information about new version can be presented. if (false && mDistribution.showEulaOrNewVersion()) { return; } setContentView(R.layout.activity_shopping); // mEditItemPosition = -1; // Automatic requeries (once a second) mUpdateInterval = 2000; mUpdating = false; // General Uris: mListUri = ShoppingContract.Lists.CONTENT_URI; mItemUri = ShoppingContract.Items.CONTENT_URI; mListItemUri = ShoppingContract.Items.CONTENT_URI; int defaultShoppingList = getLastUsedListFromPrefs(); // Handle the calling intent final Intent intent = getIntent(); final String type = intent.resolveType(this); final String action = intent.getAction(); if (action == null) { // Main action mState = STATE_MAIN; mListUri = Uri.withAppendedPath(ShoppingContract.Lists.CONTENT_URI, "" + defaultShoppingList); intent.setData(mListUri); } else if (Intent.ACTION_MAIN.equals(action)) { // Main action mState = STATE_MAIN; mListUri = Uri.withAppendedPath(ShoppingContract.Lists.CONTENT_URI, "" + defaultShoppingList); intent.setData(mListUri); } else if (Intent.ACTION_VIEW.equals(action)) { mState = STATE_VIEW_LIST; setListUriFromIntent(intent.getData(), type); } else if (Intent.ACTION_INSERT.equals(action)) { mState = STATE_VIEW_LIST; setListUriFromIntent(intent.getData(), type); } else if (Intent.ACTION_PICK.equals(action)) { mState = STATE_PICK_ITEM; mListUri = Uri.withAppendedPath(ShoppingContract.Lists.CONTENT_URI, "" + defaultShoppingList); } else if (Intent.ACTION_GET_CONTENT.equals(action)) { mState = STATE_GET_CONTENT_ITEM; mListUri = Uri.withAppendedPath(ShoppingContract.Lists.CONTENT_URI, "" + defaultShoppingList); } else if (GeneralIntents.ACTION_INSERT_FROM_EXTRAS.equals(action)) { if (ShoppingListIntents.TYPE_STRING_ARRAYLIST_SHOPPING.equals(type)) { /* * Need to insert new items from a string array in the intent * extras Use main action but add an item to the options menu * for adding extra items */ getShoppingExtras(intent); mState = STATE_MAIN; mListUri = Uri.withAppendedPath(ShoppingContract.Lists.CONTENT_URI, "" + defaultShoppingList); intent.setData(mListUri); } else if (intent.getDataString().startsWith(ShoppingContract.Lists.CONTENT_URI.toString())) { // Somewhat quick fix to pass data from ShoppingListsActivity to // this activity. // We received a valid shopping list URI: mListUri = intent.getData(); getShoppingExtras(intent); mState = STATE_MAIN; intent.setData(mListUri); } } else { // Unknown action. Log.e(TAG, "Shopping: Unknown action, exiting"); finish(); return; } // hook up all buttons, lists, edit text: createView(); // populate the lists fillListFilter(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); // Get last part of URI: int selectList; try { selectList = Integer.parseInt(mListUri.getLastPathSegment()); } catch (NumberFormatException e) { selectList = defaultShoppingList; } // select the default shopping list at the beginning: setSelectedListId(selectList); if (icicle != null) { String prevText = icicle.getString(ORIGINAL_ITEM); if (prevText != null) { mEditText.setTextKeepState(prevText); } // mTextEntryMenu = icicle.getInt(BUNDLE_TEXT_ENTRY_MENU); // mEditItemPosition = icicle.getInt(BUNDLE_CURSOR_ITEMS_POSITION); mItemUri = Uri.parse(icicle.getString(BUNDLE_ITEM_URI)); List<String> pathSegs = mItemUri.getPathSegments(); int num = pathSegs.size(); mListItemUri = Uri.withAppendedPath(mListUri, pathSegs.get(num - 1)); if (icicle.containsKey(BUNDLE_RELATION_URI)) { mRelationUri = Uri.parse(icicle.getString(BUNDLE_RELATION_URI)); } mItemsView.mMode = icicle.getInt(BUNDLE_MODE); mItemsView.mModeBeforeSearch = icicle.getInt(BUNDLE_MODE_BEFORE_SEARCH); } // set focus to the edit line: mEditText.requestFocus(); // TODO remove initFromPreferences from onCreate // we need it in resume to update after settings have changed initFromPreferences(); // now update title and fill all items onModeChanged(); mItemsView.setActionBarListener(this); mItemsView.setUndoListener(this); if ("myo".equals(BuildConfig.FLAVOR)) { try { Class myoToggleBoughtInputMethod = Class .forName("org.openintents.shopping.ui.MyoToggleBoughtInputMethod"); Constructor constructor = myoToggleBoughtInputMethod .getConstructor(new Class[] { ShoppingActivity.class, mItemsView.getClass() }); toggleBoughtInputMethod = (ToggleBoughtInputMethod) constructor .newInstance(new Object[] { this, mItemsView }); } catch (ClassNotFoundException e) { } catch (NoSuchMethodException e) { } catch (InvocationTargetException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { } } }
From source file:net.ddns.mlsoftlaberge.contactslist.ui.ContactAdminFragment.java
@Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { switch (id) { // Two main queries to load the required information case ContactDetailQuery.QUERY_ID: // This query loads main contact admins, see // ContactDetailQuery for more information. return new CursorLoader(getActivity(), mContactUri, ContactDetailQuery.PROJECTION, null, null, null); case ContactAddressQuery.QUERY_ID: // This query loads contact address admins, 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 ContactNotesQuery.QUERY_ID: // This query loads contact address admins, see // ContactAddressQuery for more information. final Uri nuri = Uri.withAppendedPath(mContactUri, Contacts.Data.CONTENT_DIRECTORY); return new CursorLoader(getActivity(), nuri, ContactNotesQuery.PROJECTION, ContactNotesQuery.SELECTION, null, null);// w w w .ja va 2 s . c om case ContactPhoneQuery.QUERY_ID: // This query loads contact address admins, see // ContactAddressQuery for more information. final Uri puri = Uri.withAppendedPath(mContactUri, Contacts.Data.CONTENT_DIRECTORY); return new CursorLoader(getActivity(), puri, ContactPhoneQuery.PROJECTION, ContactPhoneQuery.SELECTION, null, null); case ContactEmailQuery.QUERY_ID: // This query loads contact address admins, see // ContactAddressQuery for more information. final Uri euri = Uri.withAppendedPath(mContactUri, Contacts.Data.CONTENT_DIRECTORY); return new CursorLoader(getActivity(), euri, ContactEmailQuery.PROJECTION, ContactEmailQuery.SELECTION, null, null); } return null; }
From source file:com.haibison.android.anhuu.utils.ui.bookmark.BookmarkFragment.java
/** * Shows a dialog to let the user enter new name or change current name of a * bookmark./*from w w w . j av a2s . com*/ * * @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.newAlertDlg(context); View view = LayoutInflater.from(context).inflate(R.layout.anhuu_f5be488d_simple_text_input_view, null); final EditText textName = (EditText) view.findViewById(R.id.anhuu_f5be488d_text1); textName.setText(name); textName.selectAll(); textName.setHint(R.string.anhuu_f5be488d_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.anhuu_f5be488d_bookmarks_dark); dialog.setTitle(id < 0 ? R.string.anhuu_f5be488d_title_new_bookmark : R.string.anhuu_f5be488d_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.anhuu_f5be488d_msg_bookmark_name_is_invalid, Dlg.LENGTH_SHORT); return; } UI.showSoftKeyboard(textName, false); ContentValues values = new ContentValues(); values.put(BookmarkContract.COLUMN_NAME, newName); if (id >= 0) { values.put(BookmarkContract.COLUMN_MODIFICATION_TIME, DbUtils.formatNumber(new Date().getTime())); context.getContentResolver().update( ContentUris.withAppendedId(BookmarkContract.genContentIdUriBase(context), 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.genContentUri(context), null, String.format("%s = %s AND %s LIKE %s", BookmarkContract.COLUMN_PROVIDER_ID, DatabaseUtils.sqlEscapeString(providerId), BookmarkContract.COLUMN_URI, DatabaseUtils.sqlEscapeString(uri.toString())), null, null); try { if (cursor != null && cursor.moveToFirst()) { values.put(BookmarkContract.COLUMN_MODIFICATION_TIME, DbUtils.formatNumber(new Date().getTime())); context.getContentResolver().update( Uri.withAppendedPath(BookmarkContract.genContentIdUriBase(context), Uri.encode(cursor.getString( cursor.getColumnIndex(BookmarkContract._ID)))), values, null, null); } else { values.put(BookmarkContract.COLUMN_PROVIDER_ID, providerId); values.put(BookmarkContract.COLUMN_URI, uri.toString()); context.getContentResolver().insert(BookmarkContract.genContentUri(context), values); } } finally { if (cursor != null) cursor.close(); } } Dlg.toast(context, context.getString(R.string.anhuu_f5be488d_msg_done), Dlg.LENGTH_SHORT); }// 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:com.example.linhdq.test.documents.viewing.grid.DocumentGridActivity.java
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (cursor.moveToFirst()) { final int titleIndex = cursor.getColumnIndex(DocumentContentProvider.Columns.TITLE); final String oldTitle = cursor.getString(titleIndex); final int idIndex = cursor.getColumnIndex(DocumentContentProvider.Columns.ID); final String documentId = String.valueOf(cursor.getInt(idIndex)); final Uri documentUri = Uri.withAppendedPath(DocumentContentProvider.CONTENT_URI, documentId); askUserForNewTitle(oldTitle, documentUri); }//w w w . j a v a2 s. c om getSupportLoaderManager().destroyLoader(loader.getId()); }
From source file:com.pacoapp.paco.triggering.NotificationCreator.java
@SuppressLint("NewApi") private void createAlarmToCancelNotificationAtTimeout(Context context, NotificationHolder notificationHolder) { DateTime alarmTime = new DateTime(notificationHolder.getAlarmTime()); int timeoutMinutes = (int) (notificationHolder.getTimeoutMillis() / MILLIS_IN_MINUTE); DateTime timeoutTime = new DateTime(alarmTime).plusMinutes(timeoutMinutes); long elapsedDurationInMillis = timeoutTime.getMillis(); Log.info("Creating cancel alarm to timeout notification for holder: " + notificationHolder.getId() + ". experiment = " + notificationHolder.getExperimentId() + ". alarmtime = " + new DateTime(alarmTime).toString() + " timing out in " + timeoutMinutes + " minutes"); Intent ultimateIntent = new Intent(context, AlarmReceiver.class); Uri uri = Uri.withAppendedPath(NotificationHolderColumns.CONTENT_URI, notificationHolder.getId().toString()); ultimateIntent.setData(uri);/*from ww w .j av a 2s. c o m*/ ultimateIntent.putExtra(NOTIFICATION_ID, notificationHolder.getId().longValue()); PendingIntent intent = PendingIntent.getBroadcast(context.getApplicationContext(), 2, ultimateIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(intent); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { alarmManager.setExact(AlarmManager.RTC_WAKEUP, elapsedDurationInMillis, intent); } else { alarmManager.set(AlarmManager.RTC_WAKEUP, elapsedDurationInMillis, intent); } }