Example usage for android.content ContentResolver openOutputStream

List of usage examples for android.content ContentResolver openOutputStream

Introduction

In this page you can find the example usage for android.content ContentResolver openOutputStream.

Prototype

public final @Nullable OutputStream openOutputStream(@NonNull Uri uri) throws FileNotFoundException 

Source Link

Document

Synonym for #openOutputStream(Uri,String) openOutputStream(uri, "w") .

Usage

From source file:org.sufficientlysecure.keychain.util.FileHelper.java

public static void copyUriData(Context context, Uri fromUri, Uri toUri) throws IOException {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;

    try {/*w w  w . ja v a2  s. co  m*/
        ContentResolver resolver = context.getContentResolver();
        bis = new BufferedInputStream(resolver.openInputStream(fromUri));
        bos = new BufferedOutputStream(resolver.openOutputStream(toUri));
        byte[] buf = new byte[1024];
        int len;
        while ((len = bis.read(buf)) > 0) {
            bos.write(buf, 0, len);
        }
    } finally {
        try {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        } catch (IOException e) {
            // ignore, it's just stream closin'
        }
    }
}

From source file:com.chen.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 *///from  w w  w.j a va  2s  .  co  m
public static void saveAttachment(Context context, InputStream in, Attachment attachment) {
    Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    ContentValues cv = new ContentValues();
    long attachmentId = attachment.mId;
    long accountId = attachment.mAccountKey;
    String contentUri = null;
    long size;
    try {
        ContentResolver resolver = context.getContentResolver();
        if (attachment.mUiDestination == UIProvider.AttachmentDestination.CACHE) {
            Uri attUri = getAttachmentUri(accountId, attachmentId);
            size = copyFile(in, resolver.openOutputStream(attUri));
            contentUri = attUri.toString();
        } else if (Utility.isExternalStorageMounted()) {
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, new FileOutputStream(file));
            String absolutePath = file.getAbsolutePath();

            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);

            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                    false /* do not use media scanner */, attachment.mMimeType, absolutePath, size,
                    true /* show notification */);
            contentUri = dm.getUriForDownloadedFile(id).toString();

        } else {
            LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }

        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.SAVED);
    } catch (IOException e) {
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);

    // If this is an inline attachment, update the body
    if (contentUri != null && attachment.mContentId != null) {
        Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey);
        if (body != null && body.mHtmlContent != null) {
            cv.clear();
            String html = body.mHtmlContent;
            String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
            String srcContentUri = " src=\"" + contentUri + "\"";
            html = html.replaceAll(contentIdRe, srcContentUri);
            cv.put(BodyColumns.HTML_CONTENT, html);
            context.getContentResolver().update(ContentUris.withAppendedId(Body.CONTENT_URI, body.mId), cv,
                    null, null);
        }
    }
}

From source file:com.indeema.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 */// ww  w  .  j  a  v a 2s . co  m
public static void saveAttachment(Context context, InputStream in, Attachment attachment) {
    Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    ContentValues cv = new ContentValues();
    long attachmentId = attachment.mId;
    long accountId = attachment.mAccountKey;
    String contentUri = null;
    long size;
    try {
        ContentResolver resolver = context.getContentResolver();
        if (attachment.mUiDestination == UIProvider.AttachmentDestination.CACHE) {
            Uri attUri = getAttachmentUri(accountId, attachmentId);
            size = copyFile(in, resolver.openOutputStream(attUri));
            contentUri = attUri.toString();
        } else if (Utility.isExternalStorageMounted()) {
            if (attachment.mFileName == null) {
                // TODO: This will prevent a crash but does not surface the underlying problem
                // to the user correctly.
                LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment with no name: %d", attachmentId);
                throw new IOException("Can't save an attachment with no name");
            }
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, new FileOutputStream(file));
            String absolutePath = file.getAbsolutePath();

            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);

            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                    false /* do not use media scanner */, attachment.mMimeType, absolutePath, size,
                    true /* show notification */);
            contentUri = dm.getUriForDownloadedFile(id).toString();

        } else {
            LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }

        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.SAVED);
    } catch (IOException e) {
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);

    // If this is an inline attachment, update the body
    if (contentUri != null && attachment.mContentId != null) {
        Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey);
        if (body != null && body.mHtmlContent != null) {
            cv.clear();
            String html = body.mHtmlContent;
            String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
            String srcContentUri = " src=\"" + contentUri + "\"";
            html = html.replaceAll(contentIdRe, srcContentUri);
            cv.put(BodyColumns.HTML_CONTENT, html);
            context.getContentResolver().update(ContentUris.withAppendedId(Body.CONTENT_URI, body.mId), cv,
                    null, null);
        }
    }
}

From source file:Main.java

/**
 * A copy of the Android internals StoreThumbnail method, it used with the insertImage to
 * populate the android.provider.MediaStore.Images.Media#insertImage with all the correct
 * meta data. The StoreThumbnail method is private so it must be duplicated here.
 * @see android.provider.MediaStore.Images.Media (StoreThumbnail private method)
 *//*  w  w  w.j  a  v a  2 s  . com*/
private static final Bitmap storeThumbnail(ContentResolver cr, Bitmap source, long id, float width,
        float height, int kind) {

    // create the matrix to scale it
    Matrix matrix = new Matrix();

    float scaleX = width / source.getWidth();
    float scaleY = height / source.getHeight();

    matrix.setScale(scaleX, scaleY);

    Bitmap thumb = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);

    ContentValues values = new ContentValues(4);
    values.put(MediaStore.Images.Thumbnails.KIND, kind);
    values.put(MediaStore.Images.Thumbnails.IMAGE_ID, (int) id);
    values.put(MediaStore.Images.Thumbnails.HEIGHT, thumb.getHeight());
    values.put(MediaStore.Images.Thumbnails.WIDTH, thumb.getWidth());

    Uri url = cr.insert(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, values);

    try {
        OutputStream thumbOut = cr.openOutputStream(url);
        thumb.compress(Bitmap.CompressFormat.JPEG, 100, thumbOut);
        thumbOut.close();
        return thumb;
    } catch (FileNotFoundException ex) {
        return null;
    } catch (IOException ex) {
        return null;
    }
}

From source file:com.tct.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 *///from  ww  w.ja  v  a 2  s .c  om
public static long saveAttachment(Context context, InputStream in, Attachment attachment) {
    final Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    final ContentValues cv = new ContentValues();
    final long attachmentId = attachment.mId;
    final long accountId = attachment.mAccountKey;
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    String contentUri = null;
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_E
    String realUri = null; //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD
    long size = 0;

    try {
        ContentResolver resolver = context.getContentResolver();
        if (attachment.mUiDestination == UIProvider.UIPROVIDER_ATTACHMENTDESTINATION_CACHE) {
            LogUtils.i(LogUtils.TAG, "AttachmentUtilities saveAttachment when attachment destination is cache",
                    "attachment.size:" + attachment.mSize);
            Uri attUri = getAttachmentUri(accountId, attachmentId);
            size = copyFile(in, resolver.openOutputStream(attUri));
            contentUri = attUri.toString();
        } else if (Utility.isExternalStorageMounted()) {
            LogUtils.i(LogUtils.TAG, "AttachmentUtilities saveAttachment to storage",
                    "attachment.size:" + attachment.mSize);
            if (TextUtils.isEmpty(attachment.mFileName)) {
                // TODO: This will prevent a crash but does not surface the underlying problem
                // to the user correctly.
                LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment with no name: %d", attachmentId);
                throw new IOException("Can't save an attachment with no name");
            }
            //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_S
            String exchange = "com.tct.exchange";
            if (exchange.equals(context.getPackageName()) && !PermissionUtil
                    .checkPermissionAndLaunchExplain(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                throw new IOException("Can't save an attachment due to no Storage permission");
            }
            //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_E
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, new FileOutputStream(file));
            String absolutePath = file.getAbsolutePath();
            realUri = "file://" + absolutePath; //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD

            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);

            final String mimeType = TextUtils.isEmpty(attachment.mMimeType) ? "application/octet-stream"
                    : attachment.mMimeType;

            try {
                DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_S
                //Note: should use media scanner, it will allow update the
                //media provider uri column in download manager's database.
                long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                        true /* use media scanner */, mimeType, absolutePath, size,
                        true /* show notification */);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_E
                contentUri = dm.getUriForDownloadedFile(id).toString();
            } catch (final IllegalArgumentException e) {
                LogUtils.d(LogUtils.TAG, e, "IAE from DownloadManager while saving attachment");
                throw new IOException(e);
            }
        } else {
            LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }

        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.UIPROVIDER_ATTACHMENTSTATE_SAVED);
        //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_S
        if (realUri != null) {
            cv.put(AttachmentColumns.REAL_URI, realUri);
        }
        //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_E
    } catch (IOException e) {
        LogUtils.e(Logging.LOG_TAG, e, "Fail to save attachment to storage!");
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.UIPROVIDER_ATTACHMENTSTATE_FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    // If this is an inline attachment, update the body
    if (contentUri != null && attachment.mContentId != null && attachment.mContentId.length() > 0) {
        Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey);
        if (body != null && body.mHtmlContent != null) {
            cv.clear();
            String html = body.mHtmlContent;
            String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
            //TS: zhaotianyong 2015-03-23 EXCHANGE BUGFIX_899799 MOD_S
            //TS: zhaotianyong 2015-04-01 EXCHANGE BUGFIX_962560 MOD_S
            String srcContentUri = " src=\"" + contentUri + "\"";
            //TS: zhaotianyong 2015-04-01 EXCHANGE BUGFIX_962560 MOD_E
            //TS: zhaotianyong 2015-03-23 EXCHANGE BUGFIX_899799 MOD_E
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_S
            try {
                html = html.replaceAll(contentIdRe, srcContentUri);
            } catch (PatternSyntaxException e) {
                LogUtils.w(Logging.LOG_TAG, "Unrecognized backslash escape sequence in pattern");
            }
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_E
            cv.put(BodyColumns.HTML_CONTENT, html);
            Body.updateBodyWithMessageId(context, attachment.mMessageKey, cv);
            Body.restoreBodyHtmlWithMessageId(context, attachment.mMessageKey);
        }
    }
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_E
    return size;
}

From source file:ca.ualberta.cmput301w14t08.geochan.fragments.ExpandImageFragment.java

/**
 * Initializes the UI of the fragment.//www .  j av a  2 s . c  om
 */
@Override
public void onStart() {
    super.onStart();
    ProgressDialog dialog = new ProgressDialog(getActivity());
    dialog.setMessage("Downloading Image");
    ImageView imageView = (ImageView) getView().findViewById(R.id.expanded_image);
    final Bitmap image = CacheManager.getInstance().deserializeImage(id);
    if (image == null) {
        // Start the image getter thread.
        ThreadManager.startGetImage(id, imageView, dialog);
    } else {
        imageView.setImageBitmap(image);
        ThreadManager.startGetImage(id, imageView, null);
    }
    LinearLayout rlayout = (LinearLayout) getView().findViewById(R.id.expanded_image_relative);
    rlayout.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            getFragmentManager().popBackStack();
        }
    });
    Button saveButton = (Button) getView().findViewById(R.id.save_image_button);
    saveButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            ContentValues values = new ContentValues();
            values.put(Images.Media.TITLE, id);
            values.put(Images.Media.DESCRIPTION, id);
            values.put(Images.Media.MIME_TYPE, "image/jpeg");
            values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());

            Uri uri = null;
            ContentResolver contentResolver = getActivity().getContentResolver();
            try {
                uri = contentResolver.insert(Images.Media.EXTERNAL_CONTENT_URI, values);
                OutputStream imageOut = contentResolver.openOutputStream(uri);
                try {
                    image.compress(Bitmap.CompressFormat.JPEG, 90, imageOut);
                } finally {
                    imageOut.close();
                }
                Toast.makeText(getActivity(), "Saved to gallery.", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Toaster.toastShort("Failed to save to gallery.");
                if (uri != null) {
                    contentResolver.delete(uri, null, null);
                    uri = null;
                }
            }
        }
    });
}

From source file:com.ruesga.rview.fragments.SnippetFragment.java

private synchronized void saveContent(byte[] content) {
    //noinspection ConstantConditions
    Uri snippetUri = getArguments().getParcelable(EXTRA_TEMP_SNIPPET_URI);
    if (snippetUri != null && getActivity() != null) {
        try {//from  ww w . j  av a  2 s. c  om
            ContentResolver cr = getActivity().getContentResolver();
            try (OutputStream os = cr.openOutputStream(snippetUri)) {
                IOUtils.write(content, os);
                mContentSize = content.length;
            }
        } catch (IOException ex) {
            Log.e(TAG, "Cannot load content stream: " + snippetUri, ex);
        }
    }
}

From source file:com.bt.download.android.gui.Librarian.java

private void syncApplicationsProviderSupport() {
    try {/*from w  ww  . j  a va  2 s . c om*/

        List<FileDescriptor> fds = Librarian.instance().getFiles(Constants.FILE_TYPE_APPLICATIONS, 0,
                Integer.MAX_VALUE, false);

        int packagesSize = fds.size();
        String[] packages = new String[packagesSize];
        for (int i = 0; i < packagesSize; i++) {
            packages[i] = fds.get(i).album;
        }
        Arrays.sort(packages);

        List<ApplicationInfo> applications = context.getPackageManager().getInstalledApplications(0);

        int size = applications.size();

        ArrayList<String> newPackagesList = new ArrayList<String>(size);

        for (int i = 0; i < size; i++) {
            ApplicationInfo appInfo = applications.get(i);

            try {
                if (appInfo == null) {
                    continue;
                }

                newPackagesList.add(appInfo.packageName);

                File f = new File(appInfo.sourceDir);
                if (!f.canRead()) {
                    continue;
                }

                int index = Arrays.binarySearch(packages, appInfo.packageName);
                if (index >= 0) {
                    continue;
                }

                String data = appInfo.sourceDir;
                String title = appInfo.packageName;
                String packageName = appInfo.packageName;
                String version = "";

                Apk apk = new Apk(context, appInfo.sourceDir);
                String[] result = parseApk(apk);
                if (result != null) {
                    if (result[1] == null) {
                        continue;
                    }
                    title = result[1];
                    version = result[0];
                }

                ContentValues cv = new ContentValues();
                cv.put(ApplicationsColumns.DATA, data);
                cv.put(ApplicationsColumns.SIZE, f.length());
                cv.put(ApplicationsColumns.TITLE, title);
                cv.put(ApplicationsColumns.MIME_TYPE, Constants.MIME_TYPE_ANDROID_PACKAGE_ARCHIVE);
                cv.put(ApplicationsColumns.VERSION, version);
                cv.put(ApplicationsColumns.PACKAGE_NAME, packageName);

                ContentResolver cr = context.getContentResolver();

                Uri uri = cr.insert(Applications.Media.CONTENT_URI, cv);

                if (appInfo.icon != 0) {
                    try {
                        InputStream is = null;
                        OutputStream os = null;

                        try {
                            is = apk.openRawResource(appInfo.icon);
                            os = cr.openOutputStream(uri);

                            byte[] buff = new byte[4 * 1024];
                            int n = 0;
                            while ((n = is.read(buff, 0, buff.length)) != -1) {
                                os.write(buff, 0, n);
                            }

                        } finally {
                            if (os != null) {
                                os.close();
                            }
                            if (is != null) {
                                is.close();
                            }
                        }
                    } catch (Throwable e) {
                        Log.e(TAG, "Can't retrieve icon image for application " + appInfo.packageName);
                    }
                }
            } catch (Throwable e) {
                Log.e(TAG, "Error retrieving information for application " + appInfo.packageName);
            }
        }

        // clean uninstalled applications
        String[] newPackages = newPackagesList.toArray(new String[0]);
        Arrays.sort(newPackages);

        // simple way n * log(n)
        for (int i = 0; i < packagesSize; i++) {
            String packageName = packages[i];
            if (Arrays.binarySearch(newPackages, packageName) < 0) {
                ContentResolver cr = context.getContentResolver();
                cr.delete(Applications.Media.CONTENT_URI,
                        ApplicationsColumns.PACKAGE_NAME + " LIKE '%" + packageName + "%'", null);
            }
        }

    } catch (Throwable e) {
        Log.e(TAG, "Error performing initial applications provider synchronization with device", e);
    }
}

From source file:org.cryptsecure.Utility.java

/**
 * Stores an image in the gallery. This is a fixed version that stores
 * correct DATE_TAKEN so that the ordering of remains correct.
 * /*from w ww .j ava  2 s.c o m*/
 * @see android.provider.MediaStore.Images.Media#insertImage(ContentResolver,
 *      Bitmap, String, String)
 */
public static final String insertImage(ContentResolver contentResolver, Bitmap bitmap, String title,
        String description) {

    final int SAVEQUALITY = 100;

    ContentValues values = new ContentValues();
    values.put(Images.Media.TITLE, title);
    values.put(Images.Media.DISPLAY_NAME, title);
    values.put(Images.Media.DESCRIPTION, description);
    values.put(Images.Media.MIME_TYPE, "image/jpeg");
    // Fix
    values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
    values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());

    Uri url = null;
    String returnValue = null;
    boolean ok = false;

    try {
        url = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        if (bitmap != null) {
            OutputStream outputStream = contentResolver.openOutputStream(url);
            try {
                bitmap.compress(Bitmap.CompressFormat.JPEG, SAVEQUALITY, outputStream);
                ok = true;
            } catch (Exception e) {
                // ignore
            }
            outputStream.close();
        }
    } catch (Exception e) {
        // ignore
    }

    if (!ok) {
        // If something went wrong, delete the entry
        if (url != null) {
            contentResolver.delete(url, null, null);
            url = null;
        }
    }

    if (url != null) {
        returnValue = url.toString();
    }

    return returnValue;
}

From source file:com.karura.framework.plugins.Capture.java

/**
 * Called when the video view exits./*from ww w  .j a  va2  s .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").
 * @throws JSONException
 */
public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) {
    final String callId = requestCallIdMap.get(requestCode);
    final ContentResolver cr = getContext().getContentResolver();

    if (callId == null) {
        return;
    }
    requestCallIdMap.remove(requestCode);

    runInBackground(new Runnable() {
        public void run() {
            // Result received okay
            if (resultCode == Activity.RESULT_OK) {

                // An audio clip was requested
                if (requestCode == CAPTURE_AUDIO) {
                    // Get the uri of the audio clip
                    Uri data = intent.getData();
                    // create a file object from the uri
                    results.put(createMediaFile(data));

                    // Send Uri back to JavaScript for listening to audio
                    resolveWithResult(callId, results);

                } else if (requestCode == CAPTURE_IMAGE) {
                    // For some reason if I try to do:
                    // Uri data = intent.getData();
                    // It crashes in the emulator and on my phone with a null pointer exception
                    // To work around it I had to grab the code from CameraLauncher.java
                    try {
                        // 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(MIME_TYPE, IMAGE_JPEG);
                        Uri uri = null;
                        try {
                            uri = cr.insert(EXTERNAL_CONTENT_URI, values);
                        } catch (UnsupportedOperationException e) {
                            Log.d(LOG_TAG, "Can't write to external media storage.");
                            try {
                                uri = cr.insert(INTERNAL_CONTENT_URI, values);
                            } catch (UnsupportedOperationException ex) {
                                Log.d(LOG_TAG, "Can't write to internal media storage.");
                                reject(callId, CAPTURE_INTERNAL_ERR,
                                        "Error capturing image - no media storage found.");
                                return;
                            }
                        }
                        FileInputStream fis = new FileInputStream(
                                DirectoryManager.getTempDirectoryPath(getContext()) + "/Capture.jpg");
                        OutputStream os = cr.openOutputStream(uri);
                        byte[] buffer = new byte[4096];
                        int len;
                        while ((len = fis.read(buffer)) != -1) {
                            os.write(buffer, 0, len);
                        }
                        os.flush();
                        os.close();
                        fis.close();

                        // Add image to results
                        results.put(createMediaFile(uri));

                        checkForDuplicateImage();

                        // Send Uri back to JavaScript for viewing image
                        resolveWithResult(callId, results);

                    } catch (IOException e) {
                        if (BuildConfig.DEBUG) {
                            e.printStackTrace();
                        }
                        reject(callId, CAPTURE_INTERNAL_ERR, "Error capturing image.");
                    }
                } else if (requestCode == CAPTURE_VIDEO) {
                    // Get the uri of the video clip
                    Uri data = intent.getData();
                    // create a file object from the uri
                    results.put(createMediaFile(data));

                    // Send Uri back to JavaScript for viewing video
                    resolveWithResult(callId, results);
                }
            }
            // if cancelled or something else
            else {
                // user canceled the action
                rejectWithError(callId, CAPTURE_NO_MEDIA_FILES, "Canceled.");
            }
        }
    });

}