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.jobs.lib_v1.imageloader.core.download.BaseImageDownloader.java

/**
 * Retrieves {@link InputStream} of image by URI (image is accessed using {@link ContentResolver}).
 *
 * @param imageUri Image URI// www . j  a  v  a2 s . c  om
 * @param extra    Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object)
 *                 DisplayImageOptions.extraForDownloader(Object)}; can be null
 * @return {@link InputStream} of image
 * @throws FileNotFoundException if the provided URI could not be opened
 */
protected InputStream getStreamFromContent(String imageUri, Object extra) throws FileNotFoundException {
    ContentResolver res = context.getContentResolver();
    Uri uri = Uri.parse(imageUri);
    return res.openInputStream(uri);
}

From source file:com.midisheetmusicmemo.FileUri.java

/** Return the file contents as a byte array.
 *  If any IO error occurs, return null.
 *///from  ww  w  .jav a  2s.  c  o m
public byte[] getData(Activity activity) {
    try {
        byte[] data;
        int totallen, len, offset;

        // First, determine the file length
        data = new byte[4096];
        InputStream file;
        String uriString = uri.toString();
        if (uriString.startsWith("file:///android_asset/")) {
            AssetManager asset = activity.getResources().getAssets();
            String filepath = uriString.replace("file:///android_asset/", "");
            file = asset.open(filepath);
        } else if (uriString.startsWith("content://")) {
            ContentResolver resolver = activity.getContentResolver();
            file = resolver.openInputStream(uri);
        } else {
            file = new FileInputStream(uri.getPath());
        }
        totallen = 0;
        len = file.read(data, 0, 4096);
        while (len > 0) {
            totallen += len;
            len = file.read(data, 0, 4096);
        }
        file.close();

        // Now read in the data
        offset = 0;
        data = new byte[totallen];

        if (uriString.startsWith("file:///android_asset/")) {
            AssetManager asset = activity.getResources().getAssets();
            String filepath = uriString.replace("file:///android_asset/", "");
            file = asset.open(filepath);
        } else if (uriString.startsWith("content://")) {
            ContentResolver resolver = activity.getContentResolver();
            file = resolver.openInputStream(uri);
        } else {
            file = new FileInputStream(uri.getPath());
        }
        while (offset < totallen) {
            len = file.read(data, offset, totallen - offset);
            if (len <= 0) {
                throw new MidiFileException("Error reading midi file", offset);
            }
            offset += len;
        }
        file.close();
        return data;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.utils.note.rteditor.media.choose.processor.MediaProcessor.java

private InputStream processContentProviderMedia(String sourceFile) {
    ContentResolver resolver = RTApi.getApplicationContext().getContentResolver();
    Uri uri = Uri.parse(sourceFile);/*from w  w  w. j ava  2  s.c o  m*/

    InputStream in = null;
    try {
        in = resolver.openInputStream(uri);
    } catch (IOException ioe) {
        Log.e(getClass().getSimpleName(), ioe.getMessage(), ioe);
    }

    return in;
}

From source file:com.ecml.FileUri.java

/** Return the file contents as a byte array.
 *  If any IO error occurs, return null.
 *//*  ww  w. j av a 2 s.co  m*/
public byte[] getData(Activity activity) {
    try {
        byte[] data;
        int totallen, len, offset;

        // First, determine the file length
        data = new byte[4096];
        InputStream file;
        String uriString = uri.toString();
        if (uriString.startsWith("file:///android_asset/")) {
            AssetManager asset = activity.getResources().getAssets();
            String filepath = uriString.replace("file:///android_asset/", "");
            file = asset.open(filepath);
        } else if (uriString.startsWith("content://")) {
            ContentResolver resolver = activity.getContentResolver();
            file = resolver.openInputStream(uri);
        } else {
            file = new FileInputStream(uri.getPath());
        }
        totallen = 0;
        len = file.read(data, 0, 4096);
        while (len > 0) {
            totallen += len;
            len = file.read(data, 0, 4096);
        }
        file.close();

        // Now read in the data
        offset = 0;
        data = new byte[totallen];

        if (uriString.startsWith("file:///android_asset/")) {
            AssetManager asset = activity.getResources().getAssets();
            String filepath = uriString.replace("file:///android_asset/", "");
            file = asset.open(filepath);
        } else if (uriString.startsWith("content://")) {
            ContentResolver resolver = activity.getContentResolver();
            file = resolver.openInputStream(uri);
        } else {
            file = new FileInputStream(uri.getPath());
        }
        while (offset < totallen) {
            len = file.read(data, offset, totallen - offset);
            if (len <= 0) {
                throw new MidiFileException("Error reading midi file", offset);
            }
            offset += len;
        }
        return data;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.example.cuisoap.agrimac.machineRegister.driverInfoFragment.java

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        Uri license_uri = data.getData();
        Log.e("uri", license_uri.toString());
        ContentResolver cr = context.getContentResolver();
        try {/*from w w w.  ja  va 2 s.  co  m*/
            Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(license_uri));
            if (requestCode == 1) {
                //String path=getRealPathFromURI(uri);
                //System.out.println(path);
                bitmap = ImageUtils.comp(bitmap);
                license_path = ImageUtils.saveMyBitmap(bitmap, "driver");
                license_pic.setImageBitmap(bitmap);
                license_pic.setVisibility(View.VISIBLE);
                license.setVisibility(View.GONE);
                license_pic.setOnClickListener(myOnClickListener);
            }

        } catch (FileNotFoundException e) {
            Log.e("Exception", e.getMessage(), e);
        }
    } else {
        Toast.makeText(context, "?", Toast.LENGTH_SHORT).show();
    }
    super.onActivityResult(requestCode, resultCode, data);
}

From source file:com.andryr.musicplayer.images.ArtworkCache.java

@Override
protected Bitmap retrieveBitmap(Long key, int reqWidth, int reqHeight) {
    if (key == -1) {
        return null;
    }/*from w  w w . j a va2  s .c  o  m*/

    if (PrefUtils.getInstance().useFreeArtworks()) {
        return getFreeArtwork(reqWidth, reqHeight);
    }

    Uri uri = ContentUris.withAppendedId(ArtworkHelper.getArtworkUri(), key);

    try {
        if (uri != null) {
            ContentResolver res = mContext.getContentResolver();
            Bitmap bitmap = BitmapHelper.decode(res.openInputStream(uri), reqWidth, reqHeight);
            return bitmap;

        }
    } catch (IOException e) {
        Log.e(TAG, "get image from contentresolver", e);
    }

    try {
        return downloadArtwork(mContext, key, reqWidth, reqHeight);
    } catch (IOException e) {
        Log.e(TAG, "download", e);
    }

    return null;
}

From source file:com.foregroundgalleryplugin.ForegroundGalleryLauncher.java

/**
 * Called when the camera view exits.//from  www.  j a  v a  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").
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    if (resultCode == Activity.RESULT_OK) {

        Uri uri = intent.getData();
        ContentResolver resolver = this.cordova.getActivity().getContentResolver();

        try {
            Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
            bitmap = scaleBitmap(bitmap);
            this.processPicture(bitmap);
            bitmap.recycle();
            bitmap = null;
            System.gc();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            this.failPicture("Error retrieving image.");
        }
    } else if (resultCode == Activity.RESULT_CANCELED) {
        this.failPicture("Selection cancelled.");
    } else {
        this.failPicture("Selection did not complete!");
    }
}

From source file:com.regula.documentreader.MainActivity.java

private Bitmap getBitmap(Uri selectedImage) {
    ContentResolver resolver = MainActivity.this.getContentResolver();
    InputStream is = null;//from  ww w  .  j av  a  2 s.com
    try {
        is = resolver.openInputStream(selectedImage);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(is, null, options);

    //Re-reading the input stream to move it's pointer to start
    try {
        is = resolver.openInputStream(selectedImage);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, 1280, 720);
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeStream(is, null, options);
}

From source file:com.plugin.gallery.ForegroundGalleryLauncher.java

/**
 * Called when the camera view exits./* www.  ja  v a 2 s .c om*/
 * 
 * @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").
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    if (resultCode == Activity.RESULT_OK) {

        Uri uri = intent.getData();
        String fileURL = intent.getStringExtra("fileURL");
        System.out.println("fileURL = " + fileURL);
        ContentResolver resolver = this.cordova.getActivity().getContentResolver();

        try {
            Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
            bitmap = scaleBitmap(bitmap);
            this.processPicture(bitmap);
            bitmap.recycle();
            bitmap = null;
            this.callbackContext.success("" + fileURL);
            System.gc();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            this.failPicture("Error retrieving image.");
        }
    } else if (resultCode == Activity.RESULT_CANCELED) {
        this.failPicture("Selection cancelled.");
    } else {
        this.failPicture("Selection did not complete!");
    }
}

From source file:om.sstvencoder.MainActivity.java

private boolean handleIntent(Intent intent) {
    if (!isIntentTypeValid(intent.getType()) || !isIntentActionValid(intent.getAction()))
        return false;
    Uri uri = intent.hasExtra(Intent.EXTRA_STREAM) ? (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM)
            : intent.getData();//from  w ww . j a  v a  2 s  .  c om
    if (uri != null) {
        try {
            ContentResolver resolver = getContentResolver();
            mCropView.setBitmapStream(resolver.openInputStream(uri));
            mCropView.rotateImage(getOrientation(resolver, uri));
            return true;
        } catch (FileNotFoundException ex) {
            if (ex.getCause() instanceof ErrnoException) {
                if (((ErrnoException) ex.getCause()).errno == OsConstants.EACCES) {
                    requestPermissions();
                    return false;
                }
            }
            String s = getString(R.string.load_img_err_title) + ": \n" + ex.getMessage();
            Toast.makeText(this, s, Toast.LENGTH_LONG).show();
        } catch (Exception ex) {
            String s = Utility.createMessage(ex) + "\n\n" + uri + "\n\n" + intent;
            showErrorMessage(getString(R.string.load_img_err_title), ex.getMessage(), s);
        }
    } else {
        String s = getString(R.string.load_img_err_txt_unsupported);
        showErrorMessage(getString(R.string.load_img_err_title), s, s + "\n\n" + intent);
    }
    return false;
}