Example usage for android.net Uri withAppendedPath

List of usage examples for android.net Uri withAppendedPath

Introduction

In this page you can find the example usage for android.net Uri withAppendedPath.

Prototype

public static Uri withAppendedPath(Uri baseUri, String pathSegment) 

Source Link

Document

Creates a new Uri by appending an already-encoded path segment to a base Uri.

Usage

From source file:com.forktech.cmerge.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.
 *
 * @param photoData/*from  ww  w .  j av a  2 s .c  om*/
 *            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.nononsenseapps.notepad.MainActivity.java

protected void renameList(String title) {
    // I will not allow empty names for lists
    // Also must have a valid id
    if (!title.equals("") && currentListId > -1) {
        ContentValues values = new ContentValues();
        values.put(NotePad.Lists.COLUMN_NAME_TITLE, title);
        // Update list
        getContentResolver().update(/*from  w w w  . j  a v  a2s . c  o m*/
                Uri.withAppendedPath(NotePad.Lists.CONTENT_ID_URI_BASE, Long.toString(currentListId)), values,
                null, null);
        UpdateNotifier.notifyChangeList(getApplicationContext(),
                Uri.withAppendedPath(NotePad.Lists.CONTENT_ID_URI_BASE, Long.toString(currentListId)));
    }
}

From source file:com.pacoapp.paco.triggering.NotificationCreator.java

@SuppressLint("NewApi")
private void createAlarmForSnooze(Context context, NotificationHolder notificationHolder) {
    DateTime alarmTime = new DateTime(notificationHolder.getAlarmTime());
    Experiment experiment = experimentProviderUtil
            .getExperimentByServerId(notificationHolder.getExperimentId());
    Integer snoozeTime = notificationHolder.getSnoozeTime();
    if (snoozeTime == null) {
        snoozeTime = DEFAULT_SNOOZE_10_MINUTES;
    }//  w w  w  .  ja  v a 2  s. c o m
    int snoozeMinutes = snoozeTime / MILLIS_IN_MINUTE;
    DateTime timeoutMinutes = new DateTime(alarmTime).plusMinutes(snoozeMinutes);
    long snoozeDurationInMillis = timeoutMinutes.getMillis();

    Log.info("Creating snooze alarm to resound notification for holder: " + notificationHolder.getId()
            + ". experiment = " + notificationHolder.getExperimentId() + ". alarmtime = "
            + new DateTime(alarmTime).toString() + " waking up from snooze in " + timeoutMinutes + " minutes");

    Intent ultimateIntent = new Intent(context, AlarmReceiver.class);
    Uri uri = Uri.withAppendedPath(NotificationHolderColumns.CONTENT_URI,
            notificationHolder.getId().toString());
    ultimateIntent.setData(uri);
    ultimateIntent.putExtra(NOTIFICATION_ID, notificationHolder.getId().longValue());
    ultimateIntent.putExtra(SNOOZE_REPEATER_EXTRA_KEY, true);

    PendingIntent intent = PendingIntent.getBroadcast(context.getApplicationContext(), 3, 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, snoozeDurationInMillis, intent);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, snoozeDurationInMillis, intent);
    }

}

From source file:org.openintents.safe.CryptoHelper.java

/**
 * Dencrypt a file previously encrypted with
 * encryptFileWithSessionKey()./*  ww w .  j av a  2 s .com*/
 * <p/>
 * The original file is not modified
 *
 * @param ctx     Context of activity in order to store temp file
 * @param fileUri Uri to either a stream or a file to read from
 * @return If decryption is successful, returns Uri of a content
 * provider to read the plaintext file.  Upon failure,
 * return null.
 * @throws Exception
 * @author Peli
 */
public Uri decryptFileWithSessionKeyThroughContentProvider(Context ctx, Uri fileUri)
        throws CryptoHelperException {
    if (debug) {
        Log.d(TAG, "fileUri=" + fileUri.toString());
    }
    ContentResolver contentResolver = ctx.getContentResolver();

    String sessionFile = "";
    Uri resultUri = null;
    boolean result = false;

    try {
        InputStream is;
        if (fileUri.getScheme().equals("file")) {
            is = new java.io.FileInputStream(fileUri.getPath());
            if (debug) {
                Log.d(TAG, "Decrypt: Input from " + fileUri.getPath());
            }
        } else {
            is = contentResolver.openInputStream(fileUri);
            if (debug) {
                Log.d(TAG, "Decrypt: Input from " + fileUri.toString());
            }
        }
        FileOutputStream os = null;

        String decryptSession;
        try {
            // create a random session name
            decryptSession = generateSalt();
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
            String msg = "Decrypt error: " + e1.getLocalizedMessage();
            throw new CryptoHelperException(msg);
        }
        sessionFile = CryptoContentProvider.SESSION_FILE + "." + decryptSession;
        if (debug) {
            Log.d(TAG, "Decrypt: Output to " + sessionFile);
        }

        // openFileOutput creates a file in /data/data/{packagename}/files/
        // In our case, /data/data/org.openintents.safe/files/
        // This file is owned and only readable by our application
        os = ctx.openFileOutput(sessionFile, Context.MODE_PRIVATE);

        // after writing the decrypted content to a temporary file,
        // pass back a Uri that can be used to read back the contents
        resultUri = Uri.withAppendedPath(CryptoContentProvider.CONTENT_URI, "decrypt/" + decryptSession);

        result = decryptStreamWithSessionKey(is, os);

        // Close the input stream
        is.close();
        os.close();

    } catch (FileNotFoundException e) {
        Log.e(TAG, "File not found", e);
    } catch (IOException e) {
        Log.e(TAG, "IOException", e);
    }

    if (result == false) {
        resultUri = null;

        // Unsuccessful. Clean up
        ctx.deleteFile(sessionFile);
    }

    return resultUri;
}

From source file:org.kontalk.sync.Syncer.java

private String getDisplayName(ContentProviderClient client, String lookupKey, String defaultValue) {
    String displayName = null;/* w w  w.  j a v a 2 s . c o  m*/
    Cursor nameQuery = null;
    try {
        nameQuery = client.query(Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey),
                new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null, null);
        if (nameQuery.moveToFirst())
            displayName = nameQuery.getString(0);
    } catch (Exception e) {
        // ignored
    } finally {
        // close cursor
        try {
            nameQuery.close();
        } catch (Exception ignored) {
        }
    }

    return (displayName != null) ? displayName : defaultValue;
}

From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java

@Override
public int update(Uri uri, ContentValues values, 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);
    }//from  w ww.  ja  v  a2 s  .c om

    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];
            }
        }
    }

    /*
     * First, find out what records match this query, and if they refer to two
     * or more (formId,formVersion) tuples, then be sure to remove all
     * FORM_MEDIA_PATH references. Otherwise, if they are all for the same
     * tuple, and the update specifies a FORM_MEDIA_PATH, move all the
     * non-matching directories elsewhere.
     */
    Integer idValue = null;
    String tableIdValue = null;
    String formIdValue = null;
    HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>();
    boolean multiset = false;
    Cursor c = null;
    try {
        c = this.query(uri, null, whereId, whereIdArgs, null);
        if (c == null) {
            throw new SQLException(
                    "FAILED Update of " + uri + " -- query for existing row did not return a cursor");
        }
        if (c.getCount() >= 1) {
            FormIdVersion ref = null;
            c.moveToPosition(-1);
            while (c.moveToNext()) {
                idValue = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class,
                        c.getColumnIndex(FormsColumns._ID));
                tableIdValue = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.TABLE_ID));
                formIdValue = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_ID));
                String tableId = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.TABLE_ID));
                String formId = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_ID));
                String formVersion = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_VERSION));
                FormIdVersion cur = new FormIdVersion(tableId, formId, formVersion);

                int appRelativeMediaPathIdx = c.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
                String mediaPath = ODKDatabaseUtils.get().getIndexAsString(c, appRelativeMediaPathIdx);
                if (mediaPath != null) {
                    mediaDirs.put(ODKFileUtils.asAppFile(appName, mediaPath),
                            (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS);
                }

                if (ref != null && !ref.equals(cur)) {
                    multiset = true;
                    break;
                } else {
                    ref = cur;
                }
            }
        }
    } catch (Exception e) {
        log.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 (c != null) {
            c.close();
        }
    }

    if (multiset) {
        // don't let users manually update media path
        // we are referring to two or more (formId,formVersion) tuples.
        if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
            values.remove(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
        }
    } else if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
        // we are not a multiset and we are setting the media path
        // try to move all the existing non-matching media paths to
        // somewhere else...
        File mediaPath = ODKFileUtils.asAppFile(appName,
                values.getAsString(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH));
        for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) {
            File altPath = entry.getKey();
            if (!altPath.equals(mediaPath)) {
                try {
                    moveDirectory(appName, entry.getValue(), altPath);
                } catch (IOException e) {
                    e.printStackTrace();
                    log.e(t, "Attempt to move " + altPath.getAbsolutePath() + " failed: " + e.toString());
                }
            }
        }
        // OK. we have moved the existing form definitions elsewhere. We can
        // proceed with update...
    }

    // ensure that all values are correct and ignore some user-supplied
    // values...
    patchUpValues(appName, values);

    // Make sure that the necessary fields are all set
    if (values.containsKey(FormsColumns.DATE) == true) {
        Date today = new Date();
        String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time),
                Locale.getDefault()).format(today);
        values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
    }

    SQLiteDatabase db = null;
    int count;
    try {
        // OK Finally, now do the update...
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        count = db.update(DatabaseConstants.FORMS_TABLE_NAME, values, whereId, whereIdArgs);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        e.printStackTrace();
        log.w(t, "Unable to perform update " + uri);
        return 0;
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    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:edu.umbc.cs.ebiquity.mithril.parserapp.contentparsers.contacts.ContactsListFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    /**/*  w w w  .  j av a2  s  .  co m*/
     * This swaps the new cursor into the adapter. This is the point when the cursor data is passed on to the adapter. 
     */
    if (loader.getId() == ContactsQuery.QUERY_ID) {
        mAdapter.swapCursor(data);

        // 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.ichi2.anki.provider.CardContentProvider.java

@Override
public Uri insert(Uri uri, ContentValues values) {
    Timber.d("CardContentProvider.insert");
    Collection col = CollectionHelper.getInstance().getCol(getContext());
    if (col == null) {
        return null;
    }//ww  w .  j  av  a  2s.  c  o  m

    // Find out what data the user is requesting
    int match = sUriMatcher.match(uri);

    switch (match) {
    case NOTES: {
        /* Insert new note with specified fields and tags
         */
        Long modelId = values.getAsLong(FlashCardsContract.Note.MID);
        String flds = values.getAsString(FlashCardsContract.Note.FLDS);
        String tags = values.getAsString(FlashCardsContract.Note.TAGS);
        // Create empty note
        com.ichi2.libanki.Note newNote = new com.ichi2.libanki.Note(col, col.getModels().get(modelId));
        // Set fields
        String[] fldsArray = Utils.splitFields(flds);
        // Check that correct number of flds specified
        if (fldsArray.length != newNote.getFields().length) {
            throw new IllegalArgumentException("Incorrect flds argument : " + flds);
        }
        for (int idx = 0; idx < fldsArray.length; idx++) {
            newNote.setField(idx, fldsArray[idx]);
        }
        // Set tags
        if (tags != null) {
            newNote.setTagsFromStr(tags);
        }
        // Add to collection
        col.addNote(newNote);
        return Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI, Long.toString(newNote.getId()));
    }
    case NOTES_ID:
        // Note ID is generated automatically by libanki
        throw new IllegalArgumentException("Not possible to insert note with specific ID");
    case NOTES_ID_CARDS:
        // Cards are generated automatically by libanki
        throw new IllegalArgumentException("Not possible to insert cards directly (only through NOTES)");
    case NOTES_ID_CARDS_ORD:
        // Cards are generated automatically by libanki
        throw new IllegalArgumentException("Not possible to insert cards directly (only through NOTES)");
    case MODELS:
        // Get input arguments
        String modelName = values.getAsString(FlashCardsContract.Model.NAME);
        String css = values.getAsString(FlashCardsContract.Model.CSS);
        Long did = values.getAsLong(FlashCardsContract.Model.DECK_ID);
        String fieldNames = values.getAsString(FlashCardsContract.Model.FIELD_NAMES);
        Integer numCards = values.getAsInteger(FlashCardsContract.Model.NUM_CARDS);
        // Throw exception if required fields empty
        if (modelName == null || fieldNames == null || numCards == null) {
            throw new IllegalArgumentException("Model name, field_names, and num_cards can't be empty");
        }
        // Create a new model
        Models mm = col.getModels();
        JSONObject newModel = mm.newModel(modelName);
        try {
            // Add the fields
            String[] allFields = Utils.splitFields(fieldNames);
            for (String f : allFields) {
                mm.addField(newModel, mm.newField(f));
            }
            // Add some empty card templates
            for (int idx = 0; idx < numCards; idx++) {
                JSONObject t = mm.newTemplate("Card " + (idx + 1));
                t.put("qfmt", String.format("{{%s}}", allFields[0]));
                String answerField = allFields[0];
                if (allFields.length > 1) {
                    answerField = allFields[1];
                }
                t.put("afmt", String.format("{{FrontSide}}\\n\\n<hr id=answer>\\n\\n{{%s}}", answerField));
                mm.addTemplate(newModel, t);
            }
            // Add the CSS if specified
            if (css != null) {
                newModel.put("css", css);
            }
            // Add the did if specified
            if (did != null) {
                newModel.put("did", did);
            }
            // Add the model to collection (from this point on edits will require a full-sync)
            mm.add(newModel);
            mm.save(newModel); // TODO: is this necessary?
            // Get the mid and return a URI
            String mid = Long.toString(newModel.getLong("id"));
            return Uri.withAppendedPath(FlashCardsContract.Model.CONTENT_URI, mid);
        } catch (ConfirmModSchemaException e) {
            // This exception should never be thrown when inserting new models
            Timber.e(e, "Unexpected ConfirmModSchema exception adding new model %s", modelName);
            throw new IllegalArgumentException("ConfirmModSchema exception adding new model " + modelName);
        } catch (JSONException e) {
            Timber.e(e, "Could not set a field of new model %s", modelName);
            return null;
        }
    case MODELS_ID:
        // Model ID is generated automatically by libanki
        throw new IllegalArgumentException("Not possible to insert model with specific ID");
    case MODELS_ID_TEMPLATES:
        // Adding new templates after the model is created could require a full-sync
        throw new IllegalArgumentException("Templates can only be added at the time of model insertion");
    case MODELS_ID_TEMPLATES_ID:
        // Adding new templates after the model is created could require a full-sync
        throw new IllegalArgumentException("Templates can only be added at the time of model insertion");
    case SCHEDULE:
        // Doesn't make sense to insert an object into the schedule table
        throw new IllegalArgumentException("Not possible to perform insert operation on schedule");
    case DECKS:
        // Insert new deck with specified name
        String deckName = values.getAsString(FlashCardsContract.Deck.DECK_NAME);
        did = col.getDecks().id(deckName);
        return Uri.withAppendedPath(FlashCardsContract.Deck.CONTENT_ALL_URI, Long.toString(did));
    case DECK_SELECTED:
        // Can't have more than one selected deck
        throw new IllegalArgumentException("Selected deck can only be queried and updated");
    case DECKS_ID:
        // Deck ID is generated automatically by libanki
        throw new IllegalArgumentException("Not possible to insert deck with specific ID");
    default:
        // Unknown URI type
        throw new IllegalArgumentException("uri " + uri + " is not supported");
    }
}

From source file:br.com.mybaby.contatos.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  v a2 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 (Util.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.nononsenseapps.notepad.MainActivity.java

/**
 * Marks the current list and all the tasks contained in it as deleted in
 * the database. Will be deleted on next sync.
 *///from   w w w  . jav  a 2s .c  o  m
protected void deleteCurrentList() {
    Log.d("deletebug", "currentlistid: " + currentListId);
    if (currentListId > -1) {
        // Only mark as deleted so it is synced
        if (shouldMarkAsDeleted(this)) {
            ContentValues values = new ContentValues();
            values.put(NotePad.Lists.COLUMN_NAME_DELETED, 1);
            // Mark list as deleted
            getContentResolver().update(
                    Uri.withAppendedPath(NotePad.Lists.CONTENT_ID_URI_BASE, Long.toString(currentListId)),
                    values, null, null);
            // Mark tasks as hidden locally. They are deleted with the list
            // in
            // the sync
            values = new ContentValues();
            values.put(NotePad.Notes.COLUMN_NAME_DELETED, 1);
            values.put(NotePad.Notes.COLUMN_NAME_MODIFIED, 0); // Yes zero,
            // we
            // don't
            // want to
            // sync
            // tasks in
            // deleted
            // lists
            Log.d("deletebug", "marking as deleted");
            getContentResolver().update(NotePad.Notes.CONTENT_URI, values,
                    NotePad.Notes.COLUMN_NAME_LIST + " IS " + currentListId, null);
        } else {
            // Delete for real
            Log.d("deletebug", "actually deleting");
            getContentResolver().delete(
                    Uri.withAppendedPath(NotePad.Lists.CONTENT_ID_URI_BASE, Long.toString(currentListId)), null,
                    null);
        }
        Log.d("deletebug", "notify!");
        UpdateNotifier.notifyChangeList(this,
                Uri.withAppendedPath(NotePad.Lists.CONTENT_ID_URI_BASE, Long.toString(currentListId)));
        UpdateNotifier.notifyChangeNote(this);

        // Remove default setting if this is the default list
        long defaultListId = Long.parseLong(PreferenceManager.getDefaultSharedPreferences(this)
                .getString(MainPrefs.KEY_DEFAULT_LIST, "-1"));
        if (currentListId == defaultListId) {
            // Remove knowledge of default list
            SharedPreferences.Editor prefEditor = PreferenceManager.getDefaultSharedPreferences(this).edit();
            prefEditor.remove(MainPrefs.KEY_DEFAULT_LIST);
            prefEditor.commit();
        }
    }
}