Example usage for android.content ContentResolver openInputStream

List of usage examples for android.content ContentResolver openInputStream

Introduction

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

Prototype

public final @Nullable InputStream openInputStream(@NonNull Uri uri) throws FileNotFoundException 

Source Link

Document

Open a stream on to the content associated with a content URI.

Usage

From source file:com.android.email.provider.EmailMessageCursor.java

public EmailMessageCursor(final Context c, final Cursor cursor, final String htmlColumn,
        final String textColumn) {
    super(cursor);
    mHtmlColumnIndex = cursor.getColumnIndex(htmlColumn);
    mTextColumnIndex = cursor.getColumnIndex(textColumn);
    final int cursorSize = cursor.getCount();
    mHtmlParts = new SparseArray<String>(cursorSize);
    mTextParts = new SparseArray<String>(cursorSize);

    final ContentResolver cr = c.getContentResolver();

    while (cursor.moveToNext()) {
        final int position = cursor.getPosition();
        final long messageId = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
        try {/*from  w w  w.jav a 2  s.  c  o m*/
            if (mHtmlColumnIndex != -1) {
                final Uri htmlUri = Body.getBodyHtmlUriForMessageWithId(messageId);
                final InputStream in = cr.openInputStream(htmlUri);
                final String underlyingHtmlString;
                try {
                    underlyingHtmlString = IOUtils.toString(in);
                } finally {
                    in.close();
                }
                final String sanitizedHtml = HtmlSanitizer.sanitizeHtml(underlyingHtmlString);
                mHtmlParts.put(position, sanitizedHtml);
            }
        } catch (final IOException e) {
            LogUtils.v(LogUtils.TAG, e, "Did not find html body for message %d", messageId);
        }
        try {
            if (mTextColumnIndex != -1) {
                final Uri textUri = Body.getBodyTextUriForMessageWithId(messageId);
                final InputStream in = cr.openInputStream(textUri);
                final String underlyingTextString;
                try {
                    underlyingTextString = IOUtils.toString(in);
                } finally {
                    in.close();
                }
                mTextParts.put(position, underlyingTextString);
            }
        } catch (final IOException e) {
            LogUtils.v(LogUtils.TAG, e, "Did not find text body for message %d", messageId);
        }
    }
    cursor.moveToPosition(-1);
}

From source file:com.foregroundcameraplugin.ForegroundCameraLauncher.java

/**
 * Called when the camera view exits./*from   www  .j  a  va  2  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.success(getRealPathFromURI(uri, this.cordova));

            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:co.mwater.foregroundcameraplugin.ForegroundCameraLauncher.java

/**
 * Called when the camera view exits./*from  www. j  a  va  2 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").
 */
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.plugin.camera.ForegroundCameraLauncher.java

/**
 * Called when the camera view exits.// w w w. j a  v  a2  s  .  com
 *
 * @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;
                }
            }
            //This if block is added to the plugin to solve the issue which was saving portrait images in landscape with -90 degree rotetion
            if (intent.getBooleanExtra("portrait", false)) {
                Matrix matrix = new Matrix();
                matrix.preRotate(90);
                try {
                    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix,
                            true);
                } catch (Exception e) {
                    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth() / 2, bitmap.getHeight() / 2,
                            matrix, true);
                    e.printStackTrace();
                }
            }

            // 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.success(getRealPathFromURI(uri, this.cordova));

            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.tct.emailcommon.utility.AttachmentUtilities.java

public static void saveAttachmentToExternal(Context context, Attachment attachment, String path) {
    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;//from   ww w  .  j a v a 2 s . c  o m
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    final long size;
    InputStream in = null;
    OutputStream out = null;
    try {
        ContentResolver resolver = context.getContentResolver();
        if (Utility.isExternalStorageMounted()) {
            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: Gantao 2015-07-29 EMAIL BUGFIX-1055568 MOD_S
            try {
                String cachedFileUri = attachment.getCachedFileUri();
                if (TextUtils.isEmpty(cachedFileUri)) {
                    throw new IOException();
                }
                in = resolver.openInputStream(Uri.parse(cachedFileUri));
            } catch (IOException e) {
                String contentUriForOpen = attachment.getContentUri();
                if (TextUtils.isEmpty(contentUriForOpen)) {
                    throw new IOException();
                }
                in = resolver.openInputStream(Uri.parse(contentUriForOpen));
                //TS: junwei-xu 2016-03-31 EMAIL BUGFIX-1886442 ADD_S
            } catch (IllegalArgumentException e) {
                String contentUriForOpen = attachment.getContentUri();
                if (TextUtils.isEmpty(contentUriForOpen)) {
                    throw new IOException();
                }
                in = resolver.openInputStream(Uri.parse(contentUriForOpen));
            }
            //TS: junwei-xu 2016-03-31 EMAIL BUGFIX-1886442 ADD_E
            //TS: jian.xu 2016-01-20 EMAIL FEATURE-1477377 MOD_S
            //Note: we support save attachment at user designated location.
            File downloads;
            if (path != null) {
                downloads = new File(path);
            } else {
                downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            }
            //TS: jian.xu 2016-01-20 EMAIL FEATURE-1477377 MOD_E
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            out = new FileOutputStream(file);
            size = copyFile(in, out);
            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);
            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.UI_STATE, UIProvider.UIPROVIDER_ATTACHMENTSTATE_SAVED);
        // TS: Gantao 2015-06-30 EMAIL BUGFIX-1031608 ADD_S
        //Note:we have saved the attachment to sd card,so should update the attachment destination external
        cv.put(AttachmentColumns.UI_DESTINATION, UIProvider.UIPROVIDER_ATTACHMENTDESTINATION_EXTERNAL);
        // TS: Gantao 2015-06-30 EMAIL BUGFIX-1031608 ADD_E
    } catch (IOException e) {
        // Handle failures here...
        LogUtils.e(Logging.LOG_TAG, "IOException while save an attachment to external storage");
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            LogUtils.e(Logging.LOG_TAG, "ioexception while close the stream");
        }
    }
    // TS: Gantao 2015-07-29 EMAIL BUGFIX-1055568 MOD_E
    //TS: wenggangjin 2014-12-10 EMAIL BUGFIX_871936 MOD_S
    //        context.getContentResolver().update(uri, cv, null, null);
    if (cv.size() > 0) {
        context.getContentResolver().update(uri, cv, null, null);
    }
    //TS: wenggangjin 2014-12-10 EMAIL BUGFIX_871936 MOD_E
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    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\"";
            String srcContentUri = " src=\"" + contentUri + "\"";
            //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
}

From source file:info.guardianproject.notepadbot.NoteCipher.java

private void importDataStream() {
    if (mCacheWord.isLocked())
        return;/*from   w w w .  j  a v a 2s  .c om*/

    try {
        ContentResolver cr = getContentResolver();
        InputStream is = cr.openInputStream(dataStream);

        String mimeType = cr.getType(dataStream);

        byte[] data = NoteUtils.readBytesAndClose(is);

        if (data.length > NConstants.MAX_STREAM_SIZE) {
            Toast.makeText(this, R.string.err_size, Toast.LENGTH_LONG).show();
        } else {
            String title = dataStream.getLastPathSegment();
            String body = dataStream.getPath();

            new NotesDbAdapter(mCacheWord, this).createNote(title, body, data, mimeType);

            Toast.makeText(this, getString(R.string.on_import, title), Toast.LENGTH_LONG).show();

            // handleDelete();

            data = null;
            dataStream = null;
            title = null;
            body = null;

            System.gc();

            fillData();
        }

    } catch (FileNotFoundException e) {
        Log.e(NConstants.TAG, e.getMessage(), e);

    } catch (IOException e) {
        Log.e(NConstants.TAG, e.getMessage(), e);

    } catch (OutOfMemoryError e) {
        Toast.makeText(this, R.string.err_size, Toast.LENGTH_LONG).show();

    } finally {
        dataStream = null;

    }
}

From source file:com.cloudstudio.camera.ForegroundCameraLauncher.java

/**
 * Called when the camera view exits.//from  w ww .j a  va  2 s .  com
 * 
 * @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 {
                Log.d("camera", "external_content_uri:"
                        + android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                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;
                }
            }
            Log.d("camera", "uri:" + uri.toString());
            // 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.success(getRealPathFromURI(uri, this.cordova));

            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.phonegap.CameraLauncher.java

/**
 * Called when the camera view exits. /*w  ww.j a va  2  s .  com*/
 * 
 * @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;

    // If CAMERA
    if (srcType == CAMERA) {

        // If image available
        if (resultCode == Activity.RESULT_OK) {
            try {
                // Read in bitmap of captured image
                Bitmap bitmap = android.provider.MediaStore.Images.Media
                        .getBitmap(this.ctx.getContentResolver(), imageUri);

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

                // If sending filename back
                else if (destType == FILE_URI) {
                    // 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.ctx.getContentResolver()
                                .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                    } catch (UnsupportedOperationException e) {
                        System.out.println("Can't write to external media storage.");
                        try {
                            uri = this.ctx.getContentResolver().insert(
                                    android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
                        } catch (UnsupportedOperationException ex) {
                            System.out.println("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.ctx.getContentResolver().openOutputStream(uri);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                    os.close();

                    // Send Uri back to JavaScript for viewing image
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                }
                bitmap.recycle();
                bitmap = null;
                System.gc();
            } 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();
            android.content.ContentResolver resolver = this.ctx.getContentResolver();
            // If sending base64 image back
            if (destType == DATA_URL) {
                try {
                    Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
                    this.processPicture(bitmap);
                    bitmap.recycle();
                    bitmap = null;
                    System.gc();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    this.failPicture("Error retrieving image.");
                }
            }

            // If sending filename back
            else if (destType == FILE_URI) {
                this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}

From source file:org.totschnig.sendwithftp.FtpTransfer.java

private void handleSendVcard(Intent intent) {
    Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
    if (uri != null) {
        ContentResolver cr = getContentResolver();
        try {// ww w.  j  av  a2  s. co  m
            //the following would only have a chance to work if FtpTransfer would request permission READ_CONTACTS
            //we would then also need to find out a meaningful filename
            is = cr.openInputStream(uri);
            fileType = FTP.ASCII_FILE_TYPE;
            fileName = "contact.vcard";
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            Toast.makeText(getBaseContext(), "No permission to read contacts", Toast.LENGTH_SHORT).show();
            ;
        }
    }
}

From source file:com.example.cuisoap.agrimac.homePage.machineDetail.machineInfoFragment.java

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        Uri uri = data.getData();//from   www . j a  va2 s.co  m
        Log.e("uri", uri.toString());
        ContentResolver cr = context.getContentResolver();
        try {
            Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
            bitmap = ImageUtils.comp(bitmap);
            switch (requestCode) {
            case 1:
                license_uri1 = uri;
                license_pic1.setImageBitmap(bitmap);
                license_pic1.setVisibility(View.VISIBLE);
                license1.setVisibility(View.GONE);
                license_pic1.setOnClickListener(myOnClickListener);
                machineDetailData.machine_license_filepath1 = ImageUtils.saveMyBitmap(bitmap, null);
                break;
            case 2:
                license_uri2 = uri;
                license_pic2.setImageBitmap(bitmap);
                license_pic2.setVisibility(View.VISIBLE);
                license2.setVisibility(View.GONE);
                license_pic2.setOnClickListener(myOnClickListener);
                machineDetailData.machine_license_filepath2 = ImageUtils.saveMyBitmap(bitmap, null);
                break;
            }
        } catch (FileNotFoundException e) {
            Log.e("Exception", e.getMessage(), e);
        }
    } else {
        Toast.makeText(context, "?", Toast.LENGTH_SHORT).show();
    }
    super.onActivityResult(requestCode, resultCode, data);
}