Example usage for android.net Uri toString

List of usage examples for android.net Uri toString

Introduction

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

Prototype

public abstract String toString();

Source Link

Document

Returns the encoded string representation of this URI.

Usage

From source file:com.dwdesign.tweetings.util.Utils.java

public static String getImagePathFromUri(final Context context, final Uri uri) {
    if (context == null || uri == null)
        return null;

    final String media_uri_start = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString();

    if (uri.toString().startsWith(media_uri_start)) {

        final String[] proj = { MediaStore.Images.Media.DATA };
        final Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);

        if (cursor == null || cursor.getCount() <= 0)
            return null;

        final int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        cursor.moveToFirst();/*from  w w w . j  a  va 2s  .  c  o m*/

        final String path = cursor.getString(column_index);
        cursor.close();
        return path;
    } else {
        final String path = uri.getPath();
        if (path != null) {
            if (new File(path).exists())
                return path;
        }
    }
    return null;
}

From source file:com.vuze.android.remote.SessionInfo.java

public void openTorrent(final Activity activity, final Uri uri) {
    if (AndroidUtils.DEBUG) {
        Log.d(TAG, "openTorrent " + uri);
    }/*from   w ww.j a  v  a2s.  co m*/
    if (uri == null) {
        return;
    }
    String scheme = uri.getScheme();
    if (AndroidUtils.DEBUG) {
        Log.d(TAG, "openTorrent " + scheme);
    }
    if ("file".equals(scheme) || "content".equals(scheme)) {
        AndroidUtilsUI.requestPermissions(activity, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
                new Runnable() {
                    @Override
                    public void run() {
                        openTorrent_perms(activity, uri);
                    }
                }, new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, R.string.content_read_failed_perms_denied, Toast.LENGTH_LONG)
                                .show();
                    }
                });
    } else {
        openTorrent(activity, uri.toString(), (String) null);
    }
}

From source file:com.MustacheMonitor.MustacheMonitor.StacheCam.java

/**
 * Called when the camera view exits./* w w  w . j  a  v  a 2s.  c o m*/
 *
 * @param requestCode       The request code originally supplied to startActivityForResult(),
 *                          allowing you to identify who this result came from.
 * @param resultCode        The integer result code returned by the child activity through its setResult().
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;
    int rotate = 0;

    // If CAMERA
    if (srcType == CAMERA) {
        // If image available
        if (resultCode == Activity.RESULT_OK) {
            try {
                // Create an ExifHelper to save the exif data that is lost during compression
                ExifHelper exif = new ExifHelper();
                try {
                    if (this.encodingType == JPEG) {
                        exif.createInFile(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity())
                                + "/.Pic.jpg");
                        exif.readExifData();
                        rotate = exif.getOrientation();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Bitmap bitmap = null;
                Uri uri = null;

                // If sending base64 image back
                if (destType == DATA_URL) {
                    bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                    if (rotate != 0 && this.correctOrientation) {
                        bitmap = getRotatedBitmap(rotate, bitmap, exif);
                    }

                    this.processPicture(bitmap);
                    checkForDuplicateImage(DATA_URL);
                }

                // If sending filename back
                else if (destType == FILE_URI) {
                    if (!this.saveToPhotoAlbum) {
                        uri = Uri.fromFile(
                                new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()),
                                        System.currentTimeMillis() + ".jpg"));
                    } else {
                        uri = getUriFromMediaStore();
                    }

                    if (uri == null) {
                        this.failPicture("Error capturing image - no media storage found.");
                    }

                    // If all this is true we shouldn't compress the image.
                    if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                            && rotate == 0) {
                        writeUncompressedImage(uri);

                        this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                    } else {
                        bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                        if (rotate != 0 && this.correctOrientation) {
                            bitmap = getRotatedBitmap(rotate, bitmap, exif);
                        }

                        // Add compressed version of captured image to returned media store Uri
                        OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                        os.close();

                        // Restore exif data to file
                        if (this.encodingType == JPEG) {
                            String exifPath;
                            if (this.saveToPhotoAlbum) {
                                exifPath = FileUtils.getRealPathFromURI(uri, this.cordova);
                            } else {
                                exifPath = uri.getPath();
                            }
                            exif.createOutFile(exifPath);
                            exif.writeExifData();
                        }

                    }
                    // Send Uri back to JavaScript for viewing image
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                }

                this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
                bitmap = null;

            } catch (IOException e) {
                e.printStackTrace();
                this.failPicture("Error capturing image.");
            }
        }

        // If cancelled
        else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Camera cancelled.");
        }

        // If something else
        else {
            this.failPicture("Did not complete!");
        }
    }

    // If retrieving photo from library
    else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = intent.getData();

            // If you ask for video or all media type you will automatically get back a file URI
            // and there will be no attempt to resize any returned data
            if (this.mediaType != PICTURE) {
                this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
            } else {
                // This is a special case to just return the path as no scaling,
                // rotating or compression needs to be done
                if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                        && destType == FILE_URI && !this.correctOrientation) {
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                } else {
                    // Get the path to the image. Makes loading so much easier.
                    String imagePath = FileUtils.getRealPathFromURI(uri, this.cordova);
                    Log.d(LOG_TAG, "Real path = " + imagePath);
                    // If we don't have a valid image so quit.
                    if (imagePath == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to retreive path to picture!");
                        return;
                    }
                    Bitmap bitmap = getScaledBitmap(imagePath);
                    if (bitmap == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to create bitmap!");
                        return;
                    }

                    if (this.correctOrientation) {
                        String[] cols = { MediaStore.Images.Media.ORIENTATION };
                        Cursor cursor = this.cordova.getActivity().getContentResolver().query(intent.getData(),
                                cols, null, null, null);
                        if (cursor != null) {
                            cursor.moveToPosition(0);
                            rotate = cursor.getInt(0);
                            cursor.close();
                        }
                        if (rotate != 0) {
                            Matrix matrix = new Matrix();
                            matrix.setRotate(rotate);
                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                    matrix, true);
                        }
                    }

                    // If sending base64 image back
                    if (destType == DATA_URL) {
                        this.processPicture(bitmap);
                    }

                    // If sending filename back
                    else if (destType == FILE_URI) {
                        // Do we need to scale the returned file
                        if (this.targetHeight > 0 && this.targetWidth > 0) {
                            try {
                                // Create an ExifHelper to save the exif data that is lost during compression
                                String resizePath = DirectoryManager
                                        .getTempDirectoryPath(this.cordova.getActivity()) + "/resize.jpg";
                                ExifHelper exif = new ExifHelper();
                                try {
                                    if (this.encodingType == JPEG) {
                                        exif.createInFile(resizePath);
                                        exif.readExifData();
                                        rotate = exif.getOrientation();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                                OutputStream os = new FileOutputStream(resizePath);
                                bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                                os.close();

                                // Restore exif data to file
                                if (this.encodingType == JPEG) {
                                    exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.cordova));
                                    exif.writeExifData();
                                }

                                // The resized image is cached by the app in order to get around this and not have to delete you
                                // application cache I'm adding the current system time to the end of the file url.
                                this.success(
                                        new PluginResult(PluginResult.Status.OK,
                                                ("file://" + resizePath + "?" + System.currentTimeMillis())),
                                        this.callbackId);
                            } catch (Exception e) {
                                e.printStackTrace();
                                this.failPicture("Error retrieving image.");
                            }
                        } else {
                            this.success(new PluginResult(PluginResult.Status.OK, uri.toString()),
                                    this.callbackId);
                        }
                    }
                    if (bitmap != null) {
                        bitmap.recycle();
                        bitmap = null;
                    }
                    System.gc();
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}

From source file:dentex.youtube.downloader.DashboardActivity.java

private void removeFromMediaStore(File fileToDel, String mediaUriString) {
    if (mediaUriString != null) {
        Uri mediaUri = Uri.parse(mediaUriString);
        // remove media file reference from MediaStore library via ContentResolver
        if (getContentResolver().delete(mediaUri, null, null) > 0) {
            Utils.logger("d", mediaUri.toString() + " Removed", DEBUG_TAG);
        } else {/*ww  w  . ja  va  2  s  .  c o m*/
            Utils.logger("w", mediaUri.toString() + " NOT removed", DEBUG_TAG);
        }
    } else {
        Utils.logger("w", "mediaUriString for " + fileToDel.getName() + " null", DEBUG_TAG);
    }
}

From source file:co.mwater.foregroundcameraplugin.ForegroundCameraLauncher.java

/**
 * Called when the camera view exits.//from   w  ww.j  a v a2  s.co  m
 * 
 * @param requestCode
 *            The request code originally supplied to
 *            startActivityForResult(), allowing you to identify who this
 *            result came from.
 * @param resultCode
 *            The integer result code returned by the child activity through
 *            its setResult().
 * @param intent
 *            An Intent, which can return result data to the caller (various
 *            data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // If image available
    if (resultCode == Activity.RESULT_OK) {
        try {
            // Create an ExifHelper to save the exif data that is lost
            // during compression
            ExifHelper exif = new ExifHelper();
            exif.createInFile(
                    getTempDirectoryPath(this.cordova.getActivity().getApplicationContext()) + "/Pic.jpg");
            exif.readExifData();

            // Read in bitmap of captured image
            Bitmap bitmap;
            try {
                bitmap = android.provider.MediaStore.Images.Media
                        .getBitmap(this.cordova.getActivity().getContentResolver(), imageUri);
            } catch (FileNotFoundException e) {
                Uri uri = intent.getData();
                android.content.ContentResolver resolver = this.cordova.getActivity().getContentResolver();
                bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
            }

            bitmap = scaleBitmap(bitmap);

            // Create entry in media store for image
            // (Don't use insertImage() because it uses default compression
            // setting of 50 - no way to change it)
            ContentValues values = new ContentValues();
            values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = null;
            try {
                uri = this.cordova.getActivity().getContentResolver()
                        .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } catch (UnsupportedOperationException e) {
                LOG.d(LOG_TAG, "Can't write to external media storage.");
                try {
                    uri = this.cordova.getActivity().getContentResolver()
                            .insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
                } catch (UnsupportedOperationException ex) {
                    LOG.d(LOG_TAG, "Can't write to internal media storage.");
                    this.failPicture("Error capturing image - no media storage found.");
                    return;
                }
            }

            // Add compressed version of captured image to returned media
            // store Uri
            OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
            os.close();

            // Restore exif data to file
            exif.createOutFile(getRealPathFromURI(uri, this.cordova));
            exif.writeExifData();

            // Send Uri back to JavaScript for viewing image
            this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, uri.toString()));
            //                  getRealPathFromURI(uri, this.cordova))); WRONG. Needs URI

            bitmap.recycle();
            bitmap = null;
            System.gc();

            checkForDuplicateImage();
        } catch (IOException e) {
            e.printStackTrace();
            this.failPicture("Error capturing image.");
        }
    }

    // If cancelled
    else if (resultCode == Activity.RESULT_CANCELED) {
        this.failPicture("Camera cancelled.");
    }

    // If something else
    else {
        this.failPicture("Did not complete!");
    }
}

From source file:com.owncloud.android.authentication.AuthenticatorActivity.java

/**
 * Starts the OAuth 'grant type' flow to get an access token, with a GET
 * AUTHORIZATION request to the BUILT-IN authorization server.
 *//* w ww  .ja v  a 2s.  c  o m*/
private void startOauthorization() {
    // be gentle with the user
    mAuthStatusIcon = R.drawable.progress_small;
    mAuthStatusText = R.string.oauth_login_connection;
    showAuthStatus();

    // GET AUTHORIZATION request
    // Uri uri = Uri.parse(getString(R.string.oauth2_url_endpoint_auth));
    Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());
    Uri.Builder uriBuilder = uri.buildUpon();
    uriBuilder.appendQueryParameter(OAuth2Constants.KEY_RESPONSE_TYPE,
            getString(R.string.oauth2_response_type));
    uriBuilder.appendQueryParameter(OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri));
    uriBuilder.appendQueryParameter(OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id));
    uriBuilder.appendQueryParameter(OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope));
    // uriBuilder.appendQueryParameter(OAuth2Constants.KEY_STATE,
    // whateverwewant);
    uri = uriBuilder.build();
    Log_OC.d(TAG, "Starting browser to view " + uri.toString());
    Intent i = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(i);
}

From source file:com.hackensack.umc.activity.ProfileSelfieActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (selectedImageView == Constant.INSU_PROOF_FRONT || selectedImageView == Constant.INSU_PROOF_BACK
            || selectedImageView == Constant.ID_PROOF_FRONT || selectedImageView == Constant.ID_PROOF_BACK) {
        Fragment fragment = (Fragment) getSupportFragmentManager().findFragmentByTag("IsuranceFragment");
        if (fragment != null) {
            fragment.onActivityResult(requestCode, resultCode, data);
            return;
        }//  ww  w.  ja va  2s .co m
    }
    switch (requestCode) {
    case Constant.FRAGMENT_CONST_REQUEST_IMAGE_CAPTURE:
        if (resultCode == RESULT_OK) {
            /*Intent intent = new Intent(ProfileSelfieActivity.this, ActivityCropImage.class);
            intent.setData(imageUri);
            startActivityForResult(intent, Constant.CROP_IMAGE_ACTIVITY);*/

            cropPictureIntent(imageUri);
        }
        break;
    default:
        Uri imageUriFromIntent = null;
        if (resultCode == RESULT_OK) {
            try {
                if (data != null) {
                    if (selectedImageView == Constant.SELFIE) {
                        imageUriFromIntent = data.getData();
                        if (imageUriFromIntent == null) {
                            imageUriFromIntent = data.getExtras().getParcelable("data");
                        }

                        if (imageUriFromIntent == null) {
                            imageUriFromIntent = imageUri;
                        }
                        /*CameraFunctionality.setPhotoToImageView(imageUri.toString(), imgSelfie, ProfileSelfieActivity.this);
                        byte[] byteArray = getIntent().getByteArrayExtra(Constant.BITMAP_IMAGE);
                        Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
                        getImageUris(imageUri, 5,bmp,null);*/

                        /*   Bitmap bitmapImage = CameraFunctionality.unCompressedImage(data.getByteArrayExtra(Constant.BITMAP_IMAGE));
                                
                           pathSelfie=Base64Converter.createBase64StringFroImage(bitmapImage,ProfileSelfieActivity.this);*/

                        txtSefileSet.setText(R.string.done);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                imageUriFromIntent = imageUri;

            }
            try {
                Bitmap bitmapImage;
                bitmapImage = CameraFunctionality.getBitmapFromFile(imageUriFromIntent.toString(),
                        ProfileSelfieActivity.this);
                bitmapImage = CameraFunctionality.rotateBitmap(bitmapImage, imageUri.toString());

                String base64 = Base64Converter.createBase64StringFromBitmap(bitmapImage,
                        ProfileSelfieActivity.this);
                getImageUris(imageUriFromIntent, selectedImageView, null, base64);

                CameraFunctionality.setBitMapToImageView(imageUriFromIntent.toString(), bitmapImage, imgSelfie,
                        ProfileSelfieActivity.this);

                //   deleteLastFromDCIM();
                // CameraFunctionality.deleteImageAfterUploading(imageUriFromIntent.toString(),ProfileSelfieActivity.this);
                /*    ImageLoader imageLoader=new ImageLoader(ProfileSelfieActivity.this);
                imageLoader.displayImage(imageUriFromIntent.toString(),imgSelfie);*/
                //pathSelfie = imageUri;

            } catch (NullPointerException e) {

            }

        }
        break;
    }
}

From source file:com.logilite.vision.camera.CameraLauncher.java

/**
 * Applies all needed transformation to the image received from the camera.
 *
 * @param destType          In which form should we return the image
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 *//*w w  w  .  j  a v a 2s.com*/
private void processResultFromCamera(int destType, Intent intent) throws IOException {
    int rotate = 0;

    // Create an ExifHelper to save the exif data that is lost during compression
    ExifHelper exif = new ExifHelper();
    try {
        if (this.encodingType == JPEG) {
            exif.createInFile(getTempDirectoryPath() + "/.Pic.jpg");
            exif.readExifData();
            rotate = exif.getOrientation();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    Bitmap bitmap = null;
    Uri uri = null;

    // If sending base64 image back
    if (destType == DATA_URL) {
        bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
        if (bitmap == null) {
            // Try to get the bitmap from intent.
            bitmap = (Bitmap) intent.getExtras().get("data");
        }

        // Double-check the bitmap.
        if (bitmap == null) {
            Log.d(LOG_TAG, "I either have a null image path or bitmap");
            this.failPicture("Unable to create bitmap!");
            return;
        }

        if (rotate != 0 && this.correctOrientation) {
            bitmap = getRotatedBitmap(rotate, bitmap, exif);
        }

        this.processPicture(bitmap);
        checkForDuplicateImage(DATA_URL);
    }

    // If sending filename back
    else if (destType == FILE_URI || destType == NATIVE_URI) {
        if (this.saveToPhotoAlbum) {
            Uri inputUri = getUriFromMediaStore();
            //Just because we have a media URI doesn't mean we have a real file, we need to make it
            uri = Uri.fromFile(new File(FileHelper.getRealPath(inputUri, this.cordova)));
        } else {
            uri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
        }

        if (uri == null) {
            this.failPicture("Error capturing image - no media storage found.");
        }

        // If all this is true we shouldn't compress the image.
        if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                && !this.correctOrientation) {
            writeUncompressedImage(uri);

            this.callbackContext.success(uri.toString());
        } else {
            bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));

            if (rotate != 0 && this.correctOrientation) {
                bitmap = getRotatedBitmap(rotate, bitmap, exif);
            }

            // Add compressed version of captured image to returned media store Uri
            OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
            os.close();

            // Restore exif data to file
            if (this.encodingType == JPEG) {
                String exifPath;
                if (this.saveToPhotoAlbum) {
                    exifPath = FileHelper.getRealPath(uri, this.cordova);
                } else {
                    exifPath = uri.getPath();
                }
                exif.createOutFile(exifPath);
                exif.writeExifData();
            }

        }
        // Send Uri back to JavaScript for viewing image
        this.callbackContext.success(uri.toString());
    }

    this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
    bitmap = null;
}

From source file:android.com.example.contactslist.ui.ContactDetailFragment.java

/**
 * Decodes and returns the contact's thumbnail image.
 * @param contactUri The Uri of the contact containing the image.
 * @param imageSize The desired target width and height of the output image in pixels.
 * @return If a thumbnail image exists for the contact, a Bitmap image, otherwise null.
 *//*  w  w w .j a v a2  s .co  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;
}