Example usage for java.io FileNotFoundException toString

List of usage examples for java.io FileNotFoundException toString

Introduction

In this page you can find the example usage for java.io FileNotFoundException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:com.android.providers.downloads.DownloadThread.java

/**
 * Prepare the destination file to receive data.  If the file already exists, we'll set up
 * appropriately for resumption./*from   w w  w  .  j a  v a2 s . co m*/
 */
private void setupDestinationFile(State state, InnerState innerState) throws StopRequest {
    if (!TextUtils.isEmpty(state.mFilename)) { // only true if we've already run a thread for this download
        if (!Helpers.isFilenameValid(state.mFilename)) {
            // this should never happen
            throw new StopRequest(Downloads.Impl.STATUS_FILE_ERROR,
                    "found invalid internal destination filename");
        }
        // We're resuming a download that got interrupted
        File f = new File(state.mFilename);
        if (f.exists()) {
            long fileLength = f.length();
            if (fileLength == 0) {
                // The download hadn't actually started, we can restart from scratch
                f.delete();
                state.mFilename = null;
            } else if (mInfo.mETag == null && !mInfo.mNoIntegrity) {
                // This should've been caught upon failure
                f.delete();
                throw new StopRequest(Downloads.Impl.STATUS_CANNOT_RESUME,
                        "Trying to resume a download that can't be resumed");
            } else {
                // All right, we'll be able to resume this download
                try {
                    state.mStream = new FileOutputStream(state.mFilename, true);
                } catch (FileNotFoundException exc) {
                    throw new StopRequest(Downloads.Impl.STATUS_FILE_ERROR,
                            "while opening destination for resuming: " + exc.toString(), exc);
                }
                innerState.mBytesSoFar = (int) fileLength;
                if (mInfo.mTotalBytes != -1) {
                    innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes);
                }
                innerState.mHeaderETag = mInfo.mETag;
                innerState.mContinuingDownload = true;
            }
        }
    }

    if (state.mStream != null && mInfo.mDestination == Downloads.Impl.DESTINATION_EXTERNAL
            && !isDrmFile(state)) {
        closeDestination(state);
    }
}

From source file:com.qut.middleware.deployer.logic.RegisterESOELogic.java

public void execute(DeploymentBean bean) throws RegisterESOEException {
    configureDataLayer(bean);/*from   w  ww .  j  av a2s .c om*/

    /* Setup Crypto Processor with additional details */
    this.cryptoProcessor.setCertIssuerDN(bean.getCertIssuerDN());
    this.cryptoProcessor.setCertIssuerEmail(bean.getCertIssuerEmailAddress());

    try {
        //Ensure ESOE EntID gets set first (ie to 1)
        bean.setEsoeEntID(this.esoeDAO.getNextEntID());

        /* Create all crypto */
        createKeyStores(bean);

        /* Create XML descriptors for ESOE and ESOE Manager webapp */
        createESOEDescriptors(bean);
        createESOEManagerDescriptors(bean);

        /* Set expiry date of PKI data */
        Calendar expiryDate = Calendar.getInstance();
        expiryDate.add(Calendar.YEAR, this.cryptoProcessor.getCertExpiryIntervalInYears());

        /* Store all crypto in data repository */

        /* ESOE */
        this.esoeDAO.insertPKIData(bean.getEsoeIdpDescID(), expiryDate.getTime(), bean.getEsoeKeystore(),
                bean.getEsoeKeyStorePassphrase(), bean.getEsoeKeyPairName(), bean.getEsoeKeyPairPassphrase());
        this.esoeDAO.insertPKIData(bean.getEsoeAADescID(), expiryDate.getTime(), bean.getEsoeKeystore(),
                bean.getEsoeKeyStorePassphrase(), bean.getEsoeKeyPairName(), bean.getEsoeKeyPairPassphrase());
        this.esoeDAO.insertPKIData(bean.getEsoeLxacmlDescID(), expiryDate.getTime(), bean.getEsoeKeystore(),
                bean.getEsoeKeyStorePassphrase(), bean.getEsoeKeyPairName(), bean.getEsoeKeyPairPassphrase());

        this.esoeDAO.insertPublicKey(bean.getEsoeIdpDescID(), expiryDate.getTime(), bean.getEsoeKeyPairName(),
                this.cryptoProcessor.convertPublicKeyByteArray(bean.getEsoeKeyPair().getPublic()));
        this.esoeDAO.insertPublicKey(bean.getEsoeAADescID(), expiryDate.getTime(), bean.getEsoeKeyPairName(),
                this.cryptoProcessor.convertPublicKeyByteArray(bean.getEsoeKeyPair().getPublic()));
        this.esoeDAO.insertPublicKey(bean.getEsoeLxacmlDescID(), expiryDate.getTime(),
                bean.getEsoeKeyPairName(),
                this.cryptoProcessor.convertPublicKeyByteArray(bean.getEsoeKeyPair().getPublic()));

        /* ESOE Manager SPEP */
        this.esoeDAO.insertPKIData(bean.getManagerDescID(), expiryDate.getTime(), bean.getEsoeManagerKeystore(),
                bean.getEsoeManagerKeyStorePassphrase(), bean.getEsoeManagerKeyPairName(),
                bean.getEsoeManagerKeyPairPassphrase());
        this.esoeDAO.insertPublicKey(bean.getManagerDescID(), expiryDate.getTime(),
                bean.getEsoeManagerKeyPairName(),
                this.cryptoProcessor.convertPublicKeyByteArray(bean.getEsoeManagerKeyPair().getPublic()));

        /* Authentication network Metadata crypto */
        this.esoeDAO.insertMetadataPKIData(expiryDate.getTime(), bean.getEsoeMetadataKeystore(),
                bean.getEsoeMetadataKeyStorePassphrase(), bean.getEsoeMetadataKeyPairName(),
                bean.getEsoeMetadataKeyPairPassphrase());

        /*
         * Dynamically create config files for user deployments so they dont need to do manual config, nice chaps
         * aren't we.
         */
        writeESOEContent(bean);
        writeESOEManagerContent(bean);
        writeSPEPContent(bean);

    } catch (FileNotFoundException e) {
        this.logger.error(
                "FileNotFoundException when attempting to configure ESOE details " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new RegisterESOEException(
                "FileNotFoundException when attempting to configure ESOE details " + e.getLocalizedMessage());
    } catch (KeyStoreException e) {
        this.logger.error(
                "KeyStoreException when attempting to configure ESOE details " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new RegisterESOEException(
                "KeyStoreException when attempting to configure ESOE details " + e.getLocalizedMessage());
    } catch (NoSuchAlgorithmException e) {
        this.logger.error("NoSuchAlgorithmException when attempting to configure ESOE details "
                + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new RegisterESOEException("NoSuchAlgorithmException when attempting to configure ESOE details "
                + e.getLocalizedMessage());
    } catch (CertificateException e) {
        this.logger.error(
                "CertificateException when attempting to configure ESOE details " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new RegisterESOEException(
                "CertificateException when attempting to configure ESOE details " + e.getLocalizedMessage());
    } catch (CryptoException e) {
        this.logger
                .error("CryptoException when attempting to configure ESOE details " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new RegisterESOEException(
                "CryptoException when attempting to configure ESOE details " + e.getLocalizedMessage());
    } catch (IOException e) {
        this.logger.error("IOException when attempting to configure ESOE details " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new RegisterESOEException(
                "IOException when attempting to configure ESOE details " + e.getLocalizedMessage());
    } catch (RenderConfigException e) {
        this.logger.error(
                "RenderConfigException when attempting to configure ESOE details " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new RegisterESOEException(
                "RenderConfigException when attempting to configure ESOE details " + e.getLocalizedMessage());
    } catch (ESOEDAOException e) {
        this.logger
                .error("ESOEDAOException when attempting to configure ESOE details " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new RegisterESOEException(
                "ESOEDAOException when attempting to configure ESOE details " + e.getLocalizedMessage());
    }
}

From source file:com.github.diogochbittencourt.googleplaydownloader.downloader.impl.DownloadThread.java

/**
 * Prepare the destination file to receive data. If the file already exists, we'll set up appropriately for
 * resumption.//from w w  w .j a v a  2s  .c  o m
 */
private void setupDestinationFile(State state, InnerState innerState) throws StopRequest {
    if (state.mFilename != null) { // only true if we've already run a
        // thread for this download
        if (!Helpers.isFilenameValid(state.mFilename)) {
            // this should never happen
            throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
                    "found invalid internal destination filename");
        }
        // We're resuming a download that got interrupted
        File f = new File(state.mFilename);
        if (f.exists()) {
            long fileLength = f.length();
            if (fileLength == 0) {
                // The download hadn't actually started, we can restart from
                // scratch
                f.delete();
                state.mFilename = null;
            } else if (mInfo.mETag == null) {
                // This should've been caught upon failure
                f.delete();
                throw new StopRequest(DownloaderService.STATUS_CANNOT_RESUME,
                        "Trying to resume a download that can't be resumed");
            } else {
                // All right, we'll be able to resume this download
                try {
                    state.mStream = new FileOutputStream(state.mFilename, true);
                } catch (FileNotFoundException exc) {
                    throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
                            "while opening destination for resuming: " + exc.toString(), exc);
                }
                innerState.mBytesSoFar = (int) fileLength;
                if (mInfo.mTotalBytes != -1) {
                    innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes);
                }
                innerState.mHeaderETag = mInfo.mETag;
                innerState.mContinuingDownload = true;
            }
        }
    }

    if (state.mStream != null) {
        closeDestination(state);
    }
}

From source file:com.blork.anpod.util.BitmapUtils.java

public static BitmapResult fetchImage(Context context, Picture picture, int desiredWidth, int desiredHeight) {

    // First compute the cache key and cache file path for this URL
    File cacheFile = null;/*from w  ww.j  ava2  s. c  o m*/
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        Log.d("APOD", "creating cache file");
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

        if (prefs.getBoolean("archive", false)) {
            cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "APOD"
                    + File.separator + toSlug(picture.title) + ".jpg");
        } else {
            cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android"
                    + File.separator + "data" + File.separator + "com.blork.anpod" + File.separator + "cache"
                    + File.separator + toSlug(picture.title) + ".jpg");
        }
    } else {
        Log.d("APOD", "SD card not mounted");
        Log.d("APOD", "creating cache file");
        cacheFile = new File(context.getCacheDir() + File.separator + toSlug(picture.title) + ".jpg");
    }

    if (cacheFile != null && cacheFile.exists()) {
        Log.d("APOD", "Cache file exists, using it.");
        try {
            Bitmap bitmap = decodeStream(new FileInputStream(cacheFile), desiredWidth, desiredHeight);
            return new BitmapResult(bitmap, Uri.fromFile(cacheFile));
        } catch (FileNotFoundException e) {
        }
    }

    try {
        Log.d("APOD", "Not cached, fetching");
        BitmapUtils.manageCache(toSlug(picture.title), context);
        // TODO: check for HTTP caching headers
        final HttpClient httpClient = SyncUtils.getHttpClient(context.getApplicationContext());
        final HttpResponse resp = httpClient.execute(new HttpGet(picture.getFullSizeImageUrl()));
        final HttpEntity entity = resp.getEntity();

        final int statusCode = resp.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK || entity == null) {
            return null;
        }

        final byte[] respBytes = EntityUtils.toByteArray(entity);

        Log.d("APOD", "Writing cache file " + cacheFile.getName());
        try {
            cacheFile.getParentFile().mkdirs();
            cacheFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(cacheFile);
            fos.write(respBytes);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d("APOD", "Error writing to bitmap cache: " + cacheFile.toString(), e);
        } catch (IOException e) {
            Log.d("APOD", "Error writing to bitmap cache: " + cacheFile.toString(), e);
        }

        // Decode the bytes and return the bitmap.
        Log.d("APOD", "Reiszing bitmap image");

        Bitmap bitmap = decodeStream(new ByteArrayInputStream(respBytes), desiredWidth, desiredHeight);
        Log.d("APOD", "Returning bitmap image");
        return new BitmapResult(bitmap, Uri.fromFile(cacheFile));
    } catch (Exception e) {
        Log.d("APOD", "Problem while loading image: " + e.toString(), e);
    }

    return null;
}

From source file:com.google.android.vending.expansion.downloader.impl.DownloadThread.java

/**
 * Prepare the destination file to receive data. If the file already exists,
 * we'll set up appropriately for resumption.
 *//*  www  . ja  v  a2  s .c  o  m*/
private void setupDestinationFile(State state, InnerState innerState) throws StopRequest {
    if (state.mFilename != null) { // only true if we've already run a
                                   // thread for this download
        if (!Helpers.isFilenameValid(state.mFilename)) {
            // this should never happen
            throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
                    "found invalid internal destination filename");
        }
        // We're resuming a download that got interrupted
        File f = new File(state.mFilename);
        if (f.exists()) {
            long fileLength = f.length();
            if (fileLength == 0) {
                // The download hadn't actually started, we can restart from
                // scratch
                f.delete();
                state.mFilename = null;
            } else if (mInfo.mETag == null) {
                // This should've been caught upon failure
                f.delete();
                throw new StopRequest(DownloaderService.STATUS_CANNOT_RESUME,
                        "Trying to resume a download that can't be resumed");
            } else {
                // All right, we'll be able to resume this download
                try {
                    state.mStream = new FileOutputStream(state.mFilename, true);
                } catch (FileNotFoundException exc) {
                    throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
                            "while opening destination for resuming: " + exc.toString(), exc);
                }
                innerState.mBytesSoFar = (int) fileLength;
                if (mInfo.mTotalBytes != -1) {
                    innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes);
                }
                innerState.mHeaderETag = mInfo.mETag;
                innerState.mContinuingDownload = true;
            }
        }
    }

    if (state.mStream != null) {
        closeDestination(state);
    }
}

From source file:com.kircherelectronics.accelerationfilter.activity.AccelerationPlotActivity.java

/**
 * Write the logged data out to a persisted file.
 *///from w w  w  . j av a 2  s.  c  om
private void writeLogToFile() {
    Calendar c = Calendar.getInstance();
    String filename = "AccelerationFilter-" + c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-"
            + c.get(Calendar.DAY_OF_MONTH) + "-" + c.get(Calendar.HOUR) + "-" + c.get(Calendar.MINUTE) + "-"
            + c.get(Calendar.SECOND) + ".csv";

    File dir = new File(Environment.getExternalStorageDirectory() + File.separator + "AccelerationFilter"
            + File.separator + "Logs");
    if (!dir.exists()) {
        dir.mkdirs();
    }

    File file = new File(dir, filename);

    FileOutputStream fos;
    byte[] data = log.getBytes();
    try {
        fos = new FileOutputStream(file);
        fos.write(data);
        fos.flush();
        fos.close();

        CharSequence text = "Log Saved";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(this, text, duration);
        toast.show();
    } catch (FileNotFoundException e) {
        CharSequence text = e.toString();
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(this, text, duration);
        toast.show();
    } catch (IOException e) {
        // handle exception
    } finally {
        // Update the MediaStore so we can view the file without rebooting.
        // Note that it appears that the ACTION_MEDIA_MOUNTED approach is
        // now blocked for non-system apps on Android 4.4.
        MediaScannerConnection.scanFile(this, new String[] { file.getPath() }, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    @Override
                    public void onScanCompleted(final String path, final Uri uri) {

                    }
                });
    }
}

From source file:com.github.colorchief.colorchief.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    super.onActivityResult(requestCode, resultCode, resultData);

    if (requestCode == SELECT_IMAGE) {
        if (resultCode == RESULT_OK) {

            uriBitmapOriginal = resultData.getData();
            try {

                bitmapScaledOriginal = decodeImageUri(uriBitmapOriginal,
                        ((ImageView) findViewById(R.id.imageView)));
            } catch (FileNotFoundException e) {
                new AlertDialog.Builder(this).setTitle("Invalid Image or Image Error").setMessage(e.toString())
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // do nothing, clicking okay will close the dialog
                            }/*w  ww  . j  a v  a  2s.co  m*/
                        })

                        .setIcon(android.R.drawable.ic_dialog_alert).show();
            }

            bitmapLoaded = true;
            transformImage();
            updateImageViewer();

        }
    }

    if (requestCode == SELECT_ICC_IN && resultCode == RESULT_OK) {
        uriIccProfileIn = resultData.getData();

        //Log.d(TAG,"Selected ICC Profile file name and path: " + fNamePath);
        iccProfileIn.loadFromFile(uriIccProfileIn);

        if (iccProfileIn.isValidProfile()) {
            TextView textViewFileName = (TextView) findViewById(R.id.textViewICCinFileName);
            textViewFileName.setText(getUriFileName(uriIccProfileIn));
        } else {
            uriIccProfileIn = null;
            new AlertDialog.Builder(this).setTitle("Source ICC Profile Loading Error")
                    .setMessage("Not a valid ICC Profile")
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // do nothing, clicking okay will close the dialog
                        }
                    })

                    .setIcon(android.R.drawable.ic_dialog_alert).show();
        }

    }

    if (requestCode == SELECT_ICC_OUT && resultCode == RESULT_OK) {
        uriIccProfileOut = resultData.getData();

        //Log.d(TAG,"Selected ICC Profile file name and path: " + fNamePath);
        iccProfileOut.loadFromFile(uriIccProfileOut);

        if (iccProfileOut.isValidProfile()) {
            TextView textViewFileName = (TextView) findViewById(R.id.textViewICCoutFileName);
            textViewFileName.setText(getUriFileName(uriIccProfileOut));
        } else {
            uriIccProfileOut = null;
            new AlertDialog.Builder(this).setTitle("Output ICC Profile Loading Error")
                    .setMessage("Not a valid ICC Profile")
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // do nothing, clicking okay will close the dialog
                        }
                    })

                    .setIcon(android.R.drawable.ic_dialog_alert).show();
        }

    }
}

From source file:cn.keyshare.download.core.DownloadThread.java

/**
  * Prepare the destination file to receive data. If the file already exists,
  * we'll set up appropriately for resumption.
  *//*from  w  w  w. ja  v a  2  s.  com*/
 private void setupDestinationFile(State state, InnerState innerState) throws StopRequest {
     if (!TextUtils.isEmpty(state.mFilename)) { // only true if we've already
         // run a thread for this
         // download
         if (!Helpers.isFilenameValid(state.mFilename)) {
             // this should never happen
             throw new StopRequest(Downloads.STATUS_FILE_ERROR, "found invalid internal destination filename");
         }

         // We're resuming a download that got interrupted
         File f = new File(state.mFilename);

         if (f.exists()) {
             long fileLength = f.length();
             if (fileLength == 0) {
                 // The download hadn't actually started, we can restart from
                 // scratch
                 f.delete();
                 state.mFilename = null;
             } else if (mInfo.mETag == null && !mInfo.mNoIntegrity) {
                 // This should've been caught upon failure
                 f.delete();
                 throw new StopRequest(Downloads.STATUS_CANNOT_RESUME,
                         "Trying to resume a download that can't be resumed");
             } else {
                 // All right, we'll be able to resume this download
                 //DownloadServiceDownloadThread?DownloadService?????
                 if (mInfo.mTotalBytes == fileLength) {
                     throw new StopRequest(Downloads.STATUS_SUCCESS,
                             " don't need resumed download, the download is success");
                 }
                 try {
                     state.mStream = new FileOutputStream(state.mFilename, true);
                 } catch (FileNotFoundException exc) {
                     throw new StopRequest(Downloads.STATUS_FILE_ERROR,
                             "while opening destination for resuming: " + exc.toString(), exc);
                 }
                 innerState.mBytesSoFar = (int) fileLength;
                 if (mInfo.mTotalBytes != -1) {
                     innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes);
                 }
                 innerState.mHeaderETag = mInfo.mETag;
                 innerState.mContinuingDownload = true;
             }
         }
     }

     if (state.mStream != null && mInfo.mDestination == Downloads.DESTINATION_EXTERNAL) {
         closeDestination(state);
     }
 }

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.
 *///from w  w  w  .j a  v a  2  s . c  om
@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;
}