List of usage examples for android.content ContentResolver openInputStream
public final @Nullable InputStream openInputStream(@NonNull Uri uri) throws FileNotFoundException
From source file:com.github.shareme.gwschips.library.BaseRecipientAdapter.java
protected static void fetchPhoto(final RecipientEntry entry, final Uri photoThumbnailUri, final ContentResolver mContentResolver) { byte[] photoBytes = mPhotoCacheMap.get(photoThumbnailUri); if (photoBytes != null) { entry.setPhotoBytes(photoBytes); return;/*w w w.j a v a 2s .c o m*/ } final Cursor photoCursor = mContentResolver.query(photoThumbnailUri, PhotoQuery.PROJECTION, null, null, null); if (photoCursor != null) { try { if (photoCursor.moveToFirst()) { photoBytes = photoCursor.getBlob(PhotoQuery.PHOTO); entry.setPhotoBytes(photoBytes); mPhotoCacheMap.put(photoThumbnailUri, photoBytes); } } finally { photoCursor.close(); } } else { InputStream inputStream = null; ByteArrayOutputStream outputStream = null; try { inputStream = mContentResolver.openInputStream(photoThumbnailUri); final Bitmap bitmap = BitmapFactory.decodeStream(inputStream); if (bitmap != null) { outputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); photoBytes = outputStream.toByteArray(); entry.setPhotoBytes(photoBytes); mPhotoCacheMap.put(photoThumbnailUri, photoBytes); } } catch (final FileNotFoundException e) { Log.w(TAG, "Error opening InputStream for photo", e); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { Log.e(TAG, "Error closing photo input stream", e); } try { if (outputStream != null) { outputStream.close(); } } catch (IOException e) { Log.e(TAG, "Error closing photo output stream", e); } } } }
From source file:com.yk.notification.util.BitmapUtil.java
/** * A safer decodeStream method rather than the one of {@link BitmapFactory} * which will be easy to get OutOfMemory Exception while loading a big image * file./*from ww w . j a v a 2 s . co m*/ * * @param uri * * @return * @throws FileNotFoundException */ public static Bitmap safeDecodeStream(Uri uri, int targetWidth, int targetHeight, Context mContext) throws FileNotFoundException { BitmapFactory.Options options = new BitmapFactory.Options(); android.content.ContentResolver resolver = mContext.getContentResolver(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(new BufferedInputStream(resolver.openInputStream(uri), 16 * 1024), null, options); // ? float imgWidth = options.outWidth; float imgHeight = options.outHeight; // ???? int widthRatio = (int) Math.ceil(imgWidth / targetWidth); int heightRatio = (int) Math.ceil(imgHeight / targetHeight); options.inSampleSize = 1; if (widthRatio > 1 || widthRatio > 1) { if (widthRatio > heightRatio) { options.inSampleSize = widthRatio; } else { options.inSampleSize = heightRatio; } } // ? options.inJustDecodeBounds = false; return BitmapFactory.decodeStream(new BufferedInputStream(resolver.openInputStream(uri), 16 * 1024), null, options); }
From source file:com.danjarvis.documentcontract.DocumentContract.java
/** * Creates a new file from the data resolved through the provided content URI. * * @return name of created file (residing at cordova.file.dataDirectory). *///from w w w.jav a2s.c om private void createFile(JSONObject args, CallbackContext callback) { try { Uri uri; String fileName; ContentResolver contentResolver; InputStream is; FileOutputStream fs; byte[] buffer; int read = 0; uri = getUri(args); if (null == uri || !(uri.getScheme().equals(ContentResolver.SCHEME_CONTENT))) { callback.error(INVALID_URI_ERROR); return; } fileName = getFileName(args); if (null == fileName) { callback.error(INVALID_PARAMS_ERROR); return; } contentResolver = cordova.getActivity().getContentResolver(); if (null == contentResolver) { callback.error("Failed to get ContentResolver object."); return; } is = contentResolver.openInputStream(uri); fs = cordova.getActivity().openFileOutput(fileName, Context.MODE_PRIVATE); buffer = new byte[32768]; while ((read = is.read(buffer, 0, buffer.length)) != -1) { fs.write(buffer, 0, read); } fs.close(); fs.flush(); is.close(); callback.success(fileName); } catch (FileNotFoundException fe) { callback.error(fe.getMessage()); } catch (IOException ie) { callback.error(ie.getMessage()); } }
From source file:com.frostwire.android.gui.views.ImageLoader.java
private Bitmap getBitmap(Context context, byte fileType, long id) { Bitmap bmp = null;//from w w w . java 2 s. c o m try { ContentResolver cr = context.getContentResolver(); if (fileType == Constants.FILE_TYPE_PICTURES) { bmp = Images.Thumbnails.getThumbnail(cr, id, Images.Thumbnails.MICRO_KIND, null); } else if (fileType == Constants.FILE_TYPE_VIDEOS) { bmp = Video.Thumbnails.getThumbnail(cr, id, Video.Thumbnails.MICRO_KIND, null); } else if (fileType == Constants.FILE_TYPE_AUDIO) { bmp = MusicUtils.getArtwork(context, id, -1, 2); } else if (fileType == Constants.FILE_TYPE_APPLICATIONS) { InputStream is = cr.openInputStream( Uri.withAppendedPath(Applications.Media.CONTENT_URI_ITEM, String.valueOf(id))); bmp = BitmapFactory.decodeStream(is); is.close(); } } catch (Throwable e) { bmp = null; // ignore } return bmp; }
From source file:com.tack.android.image.ImageCache.java
/** * Get from disk cache./*from w w w.jav a 2s .c o m*/ * * @param data Unique identifier for which item to get * @param resolver Used to access the db cache (can be null) * @return The bitmap if found in cache, null otherwise */ public Bitmap getBitmapFromDiskCache(String data, ContentResolver resolver) { final String key = hashKeyForDisk(data); if (mCacheParams.useDBDiskCache) { if (resolver == null) return null; Uri bitmapUri = mCacheParams.baseCacheUri.buildUpon().appendEncodedPath(key).build(); InputStream inputStream = null; try { inputStream = resolver.openInputStream(bitmapUri); if (inputStream != null) { final Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } } catch (IOException e) { } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { } } } else { synchronized (mDiskCacheLock) { while (mDiskCacheStarting) { try { mDiskCacheLock.wait(); } catch (InterruptedException e) { } } if (mDiskLruCache != null) { InputStream inputStream = null; try { final DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key); if (snapshot != null) { if (BuildConfig.DEBUG) { Log.d(TAG, "Disk cache hit"); } inputStream = snapshot.getInputStream(DISK_CACHE_INDEX); if (inputStream != null) { final Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } } } catch (final IOException e) { Log.e(TAG, "getBitmapFromDiskCache - " + e); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { } } } return null; } } return null; }
From source file:nf.frex.android.FrexActivity.java
private InputStream openLocalContentStream(Uri frexDocUri) throws FileNotFoundException { ContentResolver cr = getContentResolver(); return cr.openInputStream(frexDocUri); }
From source file:com.tct.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); //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S mHtmlLinkifyColumnIndex = cursor.getColumnIndex(UIProvider.MessageColumns.BODY_HTML_LINKIFY); mHtmlLinkifyParts = new SparseArray<String>(cursorSize); mTextLinkifyColumnIndex = cursor.getColumnIndex(UIProvider.MessageColumns.BODY_TEXT_LINKIFY); mTextLinkifyParts = new SparseArray<String>(cursorSize); //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E final ContentResolver cr = c.getContentResolver(); while (cursor.moveToNext()) { final int position = cursor.getPosition(); final long messageId = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID)); // TS: chao.zhang 2015-09-14 EMAIL BUGFIX-1039046 MOD_S InputStream htmlIn = null; InputStream textIn = null; try {// ww w. ja v a 2 s.c o m if (mHtmlColumnIndex != -1) { final Uri htmlUri = Body.getBodyHtmlUriForMessageWithId(messageId); //WARNING: Actually openInput will used 2 PIPE(FD) to connect,but if some exception happen during connect, //such as fileNotFoundException,maybe the connection will not be closed. just a try!!! htmlIn = cr.openInputStream(htmlUri); final String underlyingHtmlString; try { underlyingHtmlString = IOUtils.toString(htmlIn); } finally { htmlIn.close(); htmlIn = null; } //TS: zhaotianyong 2015-04-05 EMAIL BUGFIX_964325 MOD_S final String sanitizedHtml = HtmlSanitizer.sanitizeHtml(underlyingHtmlString); mHtmlParts.put(position, sanitizedHtml); //TS: zhaotianyong 2015-04-05 EMAIL BUGFIX_964325 MOD_E //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S //NOTE: add links for sanitized html if (!TextUtils.isEmpty(sanitizedHtml)) { final String linkifyHtml = com.tct.mail.utils.Linkify.addLinks(sanitizedHtml); mHtmlLinkifyParts.put(position, linkifyHtml); } else { mHtmlLinkifyParts.put(position, ""); } //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E } } catch (final IOException e) { LogUtils.v(LogUtils.TAG, e, "Did not find html body for message %d", messageId); } catch (final OutOfMemoryError oom) { LogUtils.v(LogUtils.TAG, oom, "Terrible,OOM happen durning query EmailMessageCursor in bodyHtml,current message %d", messageId); mHtmlLinkifyParts.put(position, ""); } try { if (mTextColumnIndex != -1) { final Uri textUri = Body.getBodyTextUriForMessageWithId(messageId); textIn = cr.openInputStream(textUri); final String underlyingTextString; try { underlyingTextString = IOUtils.toString(textIn); } finally { textIn.close(); textIn = null; } mTextParts.put(position, underlyingTextString); //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S //NOTE: add links for underlying text string if (!TextUtils.isEmpty(underlyingTextString)) { final SpannableString spannable = new SpannableString(underlyingTextString); Linkify.addLinks(spannable, Linkify.EMAIL_ADDRESSES | Linkify.WEB_URLS | Linkify.PHONE_NUMBERS); final String linkifyText = Html.toHtml(spannable); mTextLinkifyParts.put(position, linkifyText); } else { mTextLinkifyParts.put(position, ""); } //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E } } catch (final IOException e) { LogUtils.v(LogUtils.TAG, e, "Did not find text body for message %d", messageId); } catch (final OutOfMemoryError oom) { LogUtils.v(LogUtils.TAG, oom, "Terrible,OOM happen durning query EmailMessageCursor in bodyText,current message %d", messageId); mTextLinkifyParts.put(position, ""); } //NOTE:Remember that this just a protective code,for better release Not used Resources. if (htmlIn != null) { try { htmlIn.close(); } catch (IOException e1) { LogUtils.v(LogUtils.TAG, e1, "IOException happen while close the htmlInput connection "); } } if (textIn != null) { try { textIn.close(); } catch (IOException e2) { LogUtils.v(LogUtils.TAG, e2, "IOException happen while close the textInput connection "); } } // TS: chao.zhang 2015-09-14 EMAIL BUGFIX-1039046 MOD_E } cursor.moveToPosition(-1); }
From source file:ir.rasen.charsoo.controller.image_loader.core.download.BaseImageDownloader.java
/** * Retrieves {@link InputStream} of image by URI (image is accessed using {@link ContentResolver}). * * @param imageUri Image URI// w ww . j a va 2 s .c o m * @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); if (isVideoContentUri(uri)) { // video thumbnail Long origId = Long.valueOf(uri.getLastPathSegment()); Bitmap bitmap = MediaStore.Video.Thumbnails.getThumbnail(res, origId, MediaStore.Images.Thumbnails.MINI_KIND, null); if (bitmap != null) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0, bos); return new ByteArrayInputStream(bos.toByteArray()); } } else if (imageUri.startsWith(CONTENT_CONTACTS_URI_PREFIX)) { // contacts photo return getContactPhotoStream(uri); } return res.openInputStream(uri); }
From source file:com.material.katha.wifidirectmp3.DeviceDetailFragment.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // User has picked an image. Transfer it to group owner i.e peer using // FileTransferService. if (requestCode >= 0 && resultCode == -1 && data != null) { // count++; Uri uri = data.getData();//from w w w . j a v a 2 s. c om String abc = uri.toString(); // System.out.println(abc); Log.d("katha", abc + "abc"); try { datapath = getPath(getActivity(), uri); Log.d("WiFiDirectActivity", datapath.substring(datapath.lastIndexOf("/") + 1, datapath.length())); } catch (URISyntaxException e) { e.printStackTrace(); } String filename = abc.substring(abc.lastIndexOf("/") + 1); pd = new ProgressDialog(getActivity()); pd.setMessage("Sending:" + datapath); pd.setButton(DialogInterface.BUTTON_NEGATIVE, "Pause", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Log.d("WiFiDirectActivity", "pause pressed"); resetafterdismiss(0); pause++; //pd.show(); } }); pd.show(); File f = new File(uri.getPath()); //long file_size = f.length(); ContentResolver cr = getActivity().getContentResolver(); InputStream is = null; int fsize = 0; try { //is=cr.openInputStream(Uri.parse(new File("DCIM/Camera/IMG_20160118_090231.jpg").toString())); is = cr.openInputStream(uri); fsize = is.available(); Log.d("WiFiDirectActivity", "File size is:" + is.available() + " " + f.getName() + "uri " + uri + "f " + f + "file name " + f.getName()); } catch (FileNotFoundException e) { e.printStackTrace(); Log.d("WifiDirectActivity", "here " + e); } catch (IOException e) { Log.d("WifiDirectActivity", "here " + e); e.printStackTrace(); } //Log.d("katha", fileext + "fileext"); //;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;change fileext = abc.substring(abc.lastIndexOf('.')); /*progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage("Sending file:"+abc); progressDialog.show(); */ // progressDialog = ProgressDialog.show(getActivity(), "Sending","Copying file :" + fileext, true, true); // makeText(getActivity(), fileext, LENGTH_LONG).show(); TextView statusText = (TextView) mContentView.findViewById(R.id.status_text); // statusText.setText("Sending: " + uri); // String devicename = "abc"; // devicename = device.deviceName; // Toast.makeText(getActivity(),devicename,Toast.LENGTH_LONG).show(); Log.d("WiFiDirectActivity", "Intent----------- " + uri); Intent serviceIntent = new Intent(getActivity(), FileTransferService.class); serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE); Log.d("WiFiDirectActivity", "Action" + FileTransferService.ACTION_SEND_FILE + "\n\n\n\n"); ////////////////////serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString()); serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, datapath); serviceIntent.putExtra(FileTransferService.FILE_SIZE, fsize); //serviceIntent.putExtra(FileTransferService.device_name,devicename); serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988); String localip = getDottedDecimalIP(getLocalIPAddress()); Localip = localip; Log.d("WiFiDirectActivity", "DEVICE_NAME: " + devicename); serviceIntent.putExtra(FileTransferService.DEVICE_NAME, devicename); if (localip.equals("192.168.49.1")) { Log.d("WiFiDirectActivity", "Flag is 0."); // devicename = device.deviceName; serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS, client_ip); serviceIntent.putExtra(FileTransferService.Client_add, client_ip); ; } else { Log.d("WiFiDirectActivity", "Flag is 1."); //devicename = device.deviceName; // Toast.makeText(getActivity(),devicename,Toast.LENGTH_LONG).show(); try { serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS, info.groupOwnerAddress.getHostAddress()); serviceIntent.putExtra(FileTransferService.Client_add, localip); } catch (Exception e) { Toast.makeText(getActivity(), "Error!!", LENGTH_LONG).show(); Log.d("WiFiDirectActivity", "error in catch!!"); return; } } getActivity().startService(serviceIntent); Log.d("WiFiDirectActivity", "here"); } else { return; } }
From source file:com.github.shareme.gwschips.library.BaseRecipientAdapter.java
private static void fetchPhotoAsync(final RecipientEntry entry, final Uri photoThumbnailUri, final BaseAdapter adapter, final ContentResolver mContentResolver) { final AsyncTask<Void, Void, byte[]> photoLoadTask = new AsyncTask<Void, Void, byte[]>() { @Override/*from ww w . jav a 2 s.c o m*/ protected byte[] doInBackground(Void... params) { // First try running a query. Images for local contacts are // loaded by sending a query to the ContactsProvider. final Cursor photoCursor = mContentResolver.query(photoThumbnailUri, PhotoQuery.PROJECTION, null, null, null); if (photoCursor != null) { try { if (photoCursor.moveToFirst()) { return photoCursor.getBlob(PhotoQuery.PHOTO); } } finally { photoCursor.close(); } } else { // If the query fails, try streaming the URI directly. // For remote directory images, this URI resolves to the // directory provider and the images are loaded by sending // an openFile call to the provider. try { InputStream is = mContentResolver.openInputStream(photoThumbnailUri); if (is != null) { byte[] buffer = new byte[BUFFER_SIZE]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { int size; while ((size = is.read(buffer)) != -1) { baos.write(buffer, 0, size); } } finally { is.close(); } return baos.toByteArray(); } } catch (IOException ex) { // ignore } } return null; } @Override protected void onPostExecute(final byte[] photoBytes) { entry.setPhotoBytes(photoBytes); if (photoBytes != null) { mPhotoCacheMap.put(photoThumbnailUri, photoBytes); if (adapter != null) adapter.notifyDataSetChanged(); } } }; photoLoadTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR); }