Example usage for android.net Uri getPath

List of usage examples for android.net Uri getPath

Introduction

In this page you can find the example usage for android.net Uri getPath.

Prototype

@Nullable
public abstract String getPath();

Source Link

Document

Gets the decoded path.

Usage

From source file:Main.java

@SuppressLint("NewApi")
public static String getRealPath(Context context, Uri uri) {
    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        if (URI_EXTERNAL_DOCUMENTS.equals(uri.getAuthority())) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }//from   w w w  .  j  a  v a2s.c  om
        } else if (URI_DOWNLOAD_DOCUMENTS.equals(uri.getAuthority())) {
            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        } else if (URI_MEDIA_DOCUMENTS.equals(uri.getAuthority())) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };
            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    } else if ("content".equalsIgnoreCase(uri.getScheme())) {
        if (URI_GOOGLE_PHOTOS.equals(uri.getAuthority()))
            return uri.getLastPathSegment();
        return getDataColumn(context, uri, null, null);
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}

From source file:com.example.scrumptious.SelectionFragment.java

private Pair<File, Integer> getImageFileAndMinDimension() {
    File photoFile = null;/* w  w  w.  j  a v  a 2  s .c  o m*/
    String photoUriString = photoUri.toString();
    if (photoUriString.startsWith("file://")) {
        photoFile = new File(photoUri.getPath());
    } else if (photoUriString.startsWith("content://")) {
        FileOutputStream photoOutputStream = null;
        InputStream contentInputStream = null;
        try {
            Uri photoUri = Uri.parse(photoUriString);
            photoFile = new File(getTempPhotoStagingDirectory(),
                    URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8"));

            photoOutputStream = new FileOutputStream(photoFile);
            contentInputStream = getActivity().getContentResolver().openInputStream(photoUri);

            byte[] buffer = new byte[1024];
            int len;
            while ((len = contentInputStream.read(buffer)) > 0) {
                photoOutputStream.write(buffer, 0, len);
            }
        } catch (FileNotFoundException fnfe) {
            Log.e(TAG, "photo not found", fnfe);
        } catch (UnsupportedEncodingException uee) {
            Log.e(TAG, "bad photo name", uee);
        } catch (IOException ioe) {
            Log.e(TAG, "can't copy photo", ioe);
        } finally {
            try {
                if (photoOutputStream != null) {
                    photoOutputStream.close();
                }
                if (contentInputStream != null) {
                    contentInputStream.close();
                }
            } catch (IOException ioe) {
                Log.e(TAG, "can't close streams");
            }
        }
    }

    if (photoFile != null) {
        InputStream is = null;
        try {
            is = new FileInputStream(photoFile);

            // We only want to get the bounds of the image, rather than load the whole thing.
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(is, null, options);

            return new Pair<>(photoFile, Math.min(options.outWidth, options.outHeight));
        } catch (Exception e) {
            return null;
        } finally {
            Utility.closeQuietly(is);
        }
    }
    return null;
}

From source file:com.frostwire.android.gui.transfers.TransferManager.java

public BittorrentDownload downloadTorrent(String uri, TorrentFetcherListener fetcherListener,
        String tempDownloadTitle) {
    String url = uri.trim();/* www .jav  a  2 s .  c  o  m*/
    try {
        if (url.contains("urn%3Abtih%3A")) {
            //fixes issue #129: over-encoded url coming from intent
            url = url.replace("urn%3Abtih%3A", "urn:btih:");
        }

        if (isAlreadyDownloadingTorrentByUri(url)) {
            return null;
        }

        Uri u = Uri.parse(url);
        String scheme = u.getScheme();
        if (!scheme.equalsIgnoreCase("file") && !scheme.equalsIgnoreCase("http")
                && !scheme.equalsIgnoreCase("https") && !scheme.equalsIgnoreCase("magnet")) {
            LOG.warn("Invalid URI scheme: " + u.toString());
            return new InvalidBittorrentDownload(R.string.torrent_scheme_download_not_supported);
        }

        BittorrentDownload download = null;

        if (fetcherListener == null) {
            if (scheme.equalsIgnoreCase("file")) {
                BTEngine.getInstance().download(new File(u.getPath()), null, null);
            } else if (scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")
                    || scheme.equalsIgnoreCase("magnet")) {
                download = new TorrentFetcherDownload(this,
                        new TorrentUrlInfo(u.toString(), tempDownloadTitle));
                bittorrentDownloadsList.add(download);
                bittorrentDownloadsMap.put(download.getInfoHash(), download);
            }
        } else {
            if (scheme.equalsIgnoreCase("file")) {
                fetcherListener.onTorrentInfoFetched(FileUtils.readFileToByteArray(new File(u.getPath())), null,
                        -1);
            } else if (scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")
                    || scheme.equalsIgnoreCase("magnet")) {
                // this executes the listener method when it fetches the bytes.
                download = new TorrentFetcherDownload(this, new TorrentUrlInfo(u.toString(), tempDownloadTitle),
                        fetcherListener);
                bittorrentDownloadsList.add(download);
                bittorrentDownloadsMap.put(download.getInfoHash(), download);
                incrementStartedTransfers();
                return download;
            }
            return null;
        }

        incrementStartedTransfers();
        return download;
    } catch (Throwable e) {
        LOG.warn("Error creating download from uri: " + url, e);
        return new InvalidBittorrentDownload(R.string.torrent_scheme_download_not_supported);
    }
}

From source file:no.nordicsemi.android.nrftoolbox.dfu.DfuActivity.java

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    if (resultCode != RESULT_OK)
        return;/* w  w w .  ja va 2  s .c om*/

    switch (requestCode) {
    case SELECT_FILE_REQ:
        // clear previous data
        mFilePath = null;
        mFileStreamUri = null;

        // and read new one
        final Uri uri = data.getData();
        /*
         * The URI returned from application may be in 'file' or 'content' schema.
         * 'File' schema allows us to create a File object and read details from if directly.
         * 
         * Data from 'Content' schema must be read by Content Provider. To do that we are using a Loader.
         */
        if (uri.getScheme().equals("file")) {
            // the direct path to the file has been returned
            final String path = uri.getPath();
            final File file = new File(path);
            mFilePath = path;

            mFileNameView.setText(file.getName());
            mFileSizeView.setText(getString(R.string.dfu_file_size_text, file.length()));
            final boolean isHexFile = mStatusOk = MimeTypeMap.getFileExtensionFromUrl(path)
                    .equalsIgnoreCase("HEX");
            mFileStatusView.setText(isHexFile ? R.string.dfu_file_status_ok : R.string.dfu_file_status_invalid);
            mUploadButton.setEnabled(mSelectedDevice != null && isHexFile);
        } else if (uri.getScheme().equals("content")) {
            // an Uri has been returned
            mFileStreamUri = uri;
            // if application returned Uri for streaming, let's us it. Does it works?
            // FIXME both Uris works with Google Drive app. Why both? What's the difference? How about other apps like DropBox?
            final Bundle extras = data.getExtras();
            if (extras != null && extras.containsKey(Intent.EXTRA_STREAM))
                mFileStreamUri = extras.getParcelable(Intent.EXTRA_STREAM);

            // file name and size must be obtained from Content Provider
            final Bundle bundle = new Bundle();
            bundle.putParcelable(EXTRA_URI, uri);
            getSupportLoaderManager().restartLoader(0, bundle, this);
        }
        break;
    default:
        break;
    }
}

From source file:Main.java

public static String getAbsolutePath(final Context context, final Uri uri) {
    // DocumentProvider
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }/*from  w ww .j  ava2s .  co m*/

        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:com.bai.android.ui.OtherActivity.java

public void changeAvatar() {
    // Prompt the user to select image from gallery or camera.
    alertDialog = new AlertDialog.Builder(OtherActivity.this);
    alertDialog.setMessage(getResources().getString(R.string.select_image_source));

    alertDialog.setPositiveButton(getResources().getString(R.string.gallery),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // remove the dialog to prevent "leakage"
                    dialog.dismiss();//from   ww w  . jav  a  2  s .  c o m

                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                    intent.setType("image/*");

                    startActivityForResult(intent, GALLERY_IMAGE_ACTIVITY_REQUEST_CODE);
                }
            });

    alertDialog.setNeutralButton(getResources().getString(R.string.camera),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Uri imageUri = getOutputMediaFileUri(); // create a file to save the image 
                    if (imageUri != null) {
                        SharedPreferences.Editor prefEditor = getSharedPreferences(SHR_PRF_APP_KEY,
                                MODE_PRIVATE).edit();
                        prefEditor.putString(SHR_PRF_IMG_URI, imageUri.getPath());
                        prefEditor.commit();
                        prefEditor = null;
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); // set the image file name

                        // start the image capture Intent
                        startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
                    }

                }

            });

    alertDialog.setNegativeButton(getResources().getString(R.string.cancel),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // close this dialog
                    dialog.dismiss();
                }
            });

    alertDialog.show();

}

From source file:com.example.zf_android.trade.ApplyDetailActivity.java

public String getRealPathFromURI(Uri contentUri) {
    try {/*from  w w w . j a  v a  2s.c  o  m*/
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = this.managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } catch (Exception e) {
        return contentUri.getPath();
    }
}

From source file:com.swater.meimeng.activity.oomimg.ImageCache.java

/**
 * A blocking call to get an image. If it's in the cache, it'll return the drawable immediately.
 * Otherwise it will download, scale, and cache the image before returning it. For non-blocking
 * use, see {@link #loadImage(int, android.net.Uri, int, int)}
 *
 * @param uri//from   w  w w.j  av a  2s . c om
 * @param width
 * @param height
 * @return
 * @throws org.apache.http.client.ClientProtocolException
 * @throws java.io.IOException
 * @throws ImageCacheException
 */
public Drawable getImage(Uri uri, int width, int height)
        throws ClientProtocolException, IOException, ImageCacheException {

    final String scaledKey = getKey(uri, width, height);

    mDownloading.lock(scaledKey);

    try {
        Drawable d = getDrawable(scaledKey);
        if (d != null) {
            return d;
        }

        Bitmap bmp = get(scaledKey);

        if (bmp == null) {
            if ("file".equals(uri.getScheme())) {
                bmp = scaleLocalImage(new File(uri.getPath()), width, height);
            } else {
                final String sourceKey = getKey(uri);

                mDownloading.lock(sourceKey);

                try {
                    if (!contains(sourceKey)) {
                        downloadImage(sourceKey, uri);
                    }
                } finally {
                    mDownloading.unlock(sourceKey);
                }

                bmp = scaleLocalImage(getFile(sourceKey), width, height);
                if (bmp == null) {
                    clear(sourceKey);
                }
            }
            put(scaledKey, bmp);

        }
        if (bmp == null) {
            throw new ImageCacheException("got null bitmap from request to scale");

        }
        d = new BitmapDrawable(mRes, bmp);
        putDrawable(scaledKey, d);

        return d;

    } finally {
        mDownloading.unlock(scaledKey);
    }
}

From source file:Main.java

public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }/*from  ww w. java2s . c  o  m*/

        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:edu.mit.mobile.android.locast.sync.AbsMediaSync.java

/**
 * Synchronize the media of the given castMedia. It will download or upload as needed.
 *
 * Blocks until the sync is complete./*from  w w w . j a va2  s.  c o m*/
 *
 * @param castMediaDir
 *            a {@link CastMedia} item uri
 * @throws SyncException
 */
public void syncItemMedia(Uri castMediaDir) throws SyncException {

    final SyncableProvider provider = getSyncableProvider(castMediaDir);
    if (provider == null) {
        Log.e(TAG, "could not sync item media: could not get local binder for syncable provider");
        return;
    }

    if (DEBUG) {
        Log.d(TAG, "syncing " + castMediaDir);
    }

    final CastMedia castMedia = (CastMedia) provider.getWrappedContentItem(castMediaDir,
            mCr.query(castMediaDir, getCastMediaProjection(), null, null, null));

    final NotificationProgressListener downloadListener = new NotificationProgressListener(this,
            NotificationProgressListener.TYPE_DOWNLOAD, R.id.locast_core__sync_download);

    try {
        final int totalItems = castMedia.getCount();

        downloadListener.setTotalItems(totalItems);

        // cache the column numbers
        final int mediaUrlCol = castMedia.getColumnIndex(CastMedia.COL_MEDIA_URL);
        final int localUriCol = castMedia.getColumnIndex(CastMedia.COL_LOCAL_URL);
        final int idCol = castMedia.getColumnIndex(CastMedia._ID);
        final int mediaDirtyCol = castMedia.getColumnIndex(CastMedia.COL_MEDIA_DIRTY);

        while (castMedia.moveToNext()) {

            final boolean keepOffline = castMedia
                    .getInt(castMedia.getColumnIndex(CastMedia.COL_KEEP_OFFLINE)) != 0;

            final String mimeType = castMedia.getString(castMedia.getColumnIndex(CastMedia.COL_MIME_TYPE));

            final boolean isImage = (mimeType != null) && mimeType.startsWith("image/");

            // we don't need to sync this
            if ("text/html".equals(mimeType)) {
                return;
            }

            final Uri locMedia = castMedia.isNull(localUriCol) ? null
                    : Uri.parse(castMedia.getString(localUriCol));
            final String pubMedia = castMedia.getString(mediaUrlCol);
            final boolean hasLocMedia = locMedia != null && new File(locMedia.getPath()).exists();
            final boolean hasPubMedia = pubMedia != null && pubMedia.length() > 0;

            final String localThumb = castMedia.getString(castMedia.getColumnIndex(CastMedia.COL_THUMB_LOCAL));

            final Uri castMediaItem = ContentUris.withAppendedId(castMediaDir, castMedia.getLong(idCol));

            final boolean isLocalDirty = castMedia.isNull(mediaDirtyCol)
                    || castMedia.getInt(mediaDirtyCol) != 0;

            if (hasLocMedia && isLocalDirty) {
                if (DEBUG) {
                    Log.d(TAG, castMediaItem + " has local media and it's dirty");
                }

                final String uploadPath = castMedia
                        .getString(castMedia.getColumnIndex(CastMedia.COL_PUBLIC_URL));
                if (uploadPath == null) {
                    Log.w(TAG, "attempted to sync " + castMediaItem + " which has a null uploadPath");
                    return;
                }

                final Uri titledItem = getTitledItemForCastMedia(castMediaItem);
                final NotificationProgressListener uploadListener = new NotificationProgressListener(this,
                        NotificationProgressListener.TYPE_UPLOAD, titledItem.hashCode());

                try {
                    uploadMedia(uploadPath, castMediaItem, titledItem, mimeType, locMedia, uploadListener);
                    uploadListener.onTransfersSuccessful();
                } finally {
                    uploadListener.onAllTransfersComplete();
                }

            } else if (!hasLocMedia && hasPubMedia) {
                if (DEBUG) {
                    Log.d(TAG, castMediaItem + " doesn't have local media, but has public media url");
                }

                // only have a public copy, so download it and store locally.
                final Uri pubMediaUri = Uri.parse(pubMedia);
                final File destfile = getFilePath(pubMediaUri);

                // the following conditions indicate that the cast media should be downloaded.
                if (keepOffline || getKeepOffline(castMediaItem, castMedia)) {

                    final boolean anythingChanged = downloadMediaFile(pubMedia, destfile, castMediaItem,
                            downloadListener);

                    // the below is inverted from what seems logical, because
                    // downloadMediaFile()
                    // will actually update the castmedia if it downloads anything. We'll only
                    // be
                    // getting here if we don't have any local record of the file, so we should
                    // make
                    // the association by ourselves.
                    if (!anythingChanged) {
                        File thumb = null;
                        if (isImage && localThumb == null) {
                            thumb = destfile;
                        }
                        updateLocalFile(castMediaDir, destfile, thumb);
                        // disabled to avoid spamming the user with downloaded
                        // items.
                        // checkForMediaEntry(castMediaUri, pubMediaUri, mimeType);
                    }
                }
            } else {
                // ensure we tell the listener that we finished
                downloadListener.onTransferComplete(castMediaItem);
            }
        }
        downloadListener.onTransfersSuccessful();
    } finally {
        downloadListener.onAllTransfersComplete();
        castMedia.close();
    }

}