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")
/**//w  w  w.j  a  va 2  s .c o  m
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.<br>
 * <br>
 * Callers should check whether the path is local before assuming it
 * represents a local file.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @see #isLocal(String)
 * @see #getFile(Context, Uri)
 * @author paulburke
 */
public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= 19;

    // 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];
            }

            // TODO handle non-primary volumes
        }
        // 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 the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:ca.psiphon.ploggy.FragmentComposeMessage.java

private void setPicture(Uri pictureUri) {
    // Try to use the MediaStore for gallery selections; otherwise, treat
    // the URI as a filesystem path.
    String path = null;//from   ww w.  jav  a2s  .c o  m
    String mimeType = null;
    Cursor cursor = null;
    try {
        String[] projection = { MediaStore.Images.Media.DATA, MediaStore.Images.Media.MIME_TYPE };
        cursor = getActivity().getContentResolver().query(pictureUri, projection, null, null, null);
        if (cursor != null) {
            int dataColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
            int mimeTypeColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.MIME_TYPE);
            if (dataColumnIndex != -1 && mimeTypeColumnIndex != -1) {
                cursor.moveToFirst();
                path = cursor.getString(dataColumnIndex);
                mimeType = cursor.getString(mimeTypeColumnIndex);
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    if (mimeType == null) {
        // TODO: vs. MimeTypeMap.getMimeTypeFromExtension?
        mimeType = getActivity().getContentResolver().getType(pictureUri);
        if (mimeType == null) {
            mimeType = "application/octet-stream";
        }
    }

    // For non-MediaStore cases
    if (path == null) {
        path = pictureUri.getPath();
    }

    // Abort when no path
    if (path == null) {
        return;
    }

    // Show a thumbnail; also, hide the add picture button (user can change picture by touching thumbnail instead).
    mSetPictureButton.setVisibility(View.GONE);
    mPictureThumbnail.setVisibility(View.VISIBLE);
    if (Pictures.loadThumbnail(getActivity(), new File(path), mPictureThumbnail)) {
        // These fields hold the picture values used when the message is sent
        mPicturePath = path;
        mPictureMimeType = mimeType;
    } else {
        mPicturePath = null;
        mPictureMimeType = null;
    }
}

From source file:ca.rmen.android.networkmonitor.app.prefs.PreferenceFragmentActivity.java

@Override
public void onOkClicked(int actionId, Bundle extras) {
    Log.v(TAG, "onClicked, actionId=" + actionId + ", extras = " + extras);
    mUserInput = true;// www .j a v a  2s.c  om
    // Import the database in a background thread.
    if (actionId == ID_ACTION_IMPORT) {
        final Uri uri = extras.getParcelable(EXTRA_IMPORT_URI);
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {

            @Override
            protected void onPreExecute() {
                DialogFragmentFactory.showProgressDialog(PreferenceFragmentActivity.this,
                        getString(R.string.progress_dialog_message), ProgressDialog.STYLE_SPINNER,
                        PROGRESS_DIALOG_FRAGMENT_TAG);
            }

            @Override
            protected Boolean doInBackground(Void... params) {
                try {
                    Log.v(TAG, "Importing db from " + uri);
                    DBImport.importDB(PreferenceFragmentActivity.this, uri);
                    return true;
                } catch (Exception e) {
                    Log.e(TAG, "Error importing db: " + e.getMessage(), e);
                    return false;
                }
            }

            @Override
            protected void onPostExecute(Boolean result) {
                ProgressDialogFragment dialogFragment = (ProgressDialogFragment) getSupportFragmentManager()
                        .findFragmentByTag(PROGRESS_DIALOG_FRAGMENT_TAG);
                if (dialogFragment != null)
                    dialogFragment.dismissAllowingStateLoss();
                String toastText = result ? getString(R.string.import_successful, uri.getPath())
                        : getString(R.string.import_failed, uri.getPath());
                Toast.makeText(PreferenceFragmentActivity.this, toastText, Toast.LENGTH_SHORT).show();
                finish();
            }
        };
        task.execute();
    } else if (actionId == ID_ACTION_LOCATION_SETTINGS) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
        finish();
    }
}

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 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        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];
                }//w  w  w.  ja  v  a2  s.  co m

                // TODO handle non-primary volumes
            }
            // 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.android.music.MediaPlaybackActivity.java

private void startPlayback() {

    if (mService == null)
        return;//ww w .ja v a2s. com
    Intent intent = getIntent();
    String filename = "";
    Uri uri = intent.getData();
    if (uri != null && uri.toString().length() > 0) {
        // If this is a file:// URI, just use the path directly instead
        // of going through the open-from-filedescriptor codepath.
        String scheme = uri.getScheme();
        if ("file".equals(scheme)) {
            filename = uri.getPath();
        } else {
            filename = uri.toString();
        }
        try {
            mService.stop();
            mService.openFile(filename);
            mService.play();
            setIntent(new Intent());
        } catch (Exception ex) {
            Log.d("MediaPlaybackActivity", "couldn't start playback: " + ex);
        }
    }

    updateTrackInfo();
    long next = refreshNow();
    queueNextRefresh(next);
}

From source file:com.luorrak.ouroboros.reply.ReplyCommentFragment.java

/**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders./*  w ww .ja  v  a 2s.co m*/
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @author paulburke
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
private 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];
            }

            // TODO handle non-primary volumes
        }
        // 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.mobicage.rogerthat.util.ui.SendMessageView.java

private void copyVideoFile(final Uri selectedVideo) {
    final ContentResolver cr = mActivity.getContentResolver();
    final ProgressDialog progressDialog = showProcessing();

    new SafeAsyncTask<Object, Object, Boolean>() {
        @Override/*from w  w w.j  a  va2s  .co m*/
        protected Boolean safeDoInBackground(Object... params) {
            L.d("Processing video: " + selectedVideo.toString());
            try {
                if (mTmpUploadFile.getAbsolutePath().equals(selectedVideo.getPath())) {
                    return true;
                } else {
                    InputStream is = cr.openInputStream(selectedVideo);
                    if (is != null) {
                        try {
                            OutputStream out = new FileOutputStream(mTmpUploadFile);
                            try {
                                IOUtils.copy(is, out, 1024);
                            } finally {
                                out.close();
                            }
                        } finally {
                            is.close();
                        }
                        return true;
                    }
                }
            } catch (FileNotFoundException e) {
                L.d(e);
            } catch (Exception e) {
                L.bug("Unknown exception occured while processing video: " + selectedVideo.toString(), e);
            }

            return false;
        };

        @Override
        protected void safeOnPostExecute(Boolean result) {
            progressDialog.dismiss();
            if (result) {
                setVideoSelected();
            } else {
                UIUtils.showLongToast(mActivity, mActivity.getString(R.string.error_please_try_again));
            }
        }

        @Override
        protected void safeOnCancelled(Boolean result) {
        }

        @Override
        protected void safeOnProgressUpdate(Object... values) {
        }

        @Override
        protected void safeOnPreExecute() {
        };
    }.execute();
}

From source file:org.planetmono.dcuploader.ActivityUploader.java

private Bitmap getBitmapThumbnail(Uri uri) {
    Bitmap b = null;/*from   w ww.j a  v a  2  s  .c  om*/
    try {
        b = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
    } catch (FileNotFoundException e1) {
        try {
            b = BitmapFactory.decodeStream(new FileInputStream(uri.getPath()));
        } catch (FileNotFoundException e2) {
            return Bitmap.createBitmap(64, 64, Bitmap.Config.ARGB_4444);
        }
    }

    int orientation = queryOrientation(uri);

    Bitmap resized = BitmapHelper.getResizedBitmap(b, 64, BitmapHelper.Axis.Vertical, orientation);
    b.recycle();

    return resized;
}

From source file:com.chatwing.whitelabel.activities.CommunicationActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    LogUtils.v("onActivityResult " + requestCode + ":" + resultCode);
    mCurrentCommunicationMode.onActivityResult(requestCode, resultCode, intent);
    if (requestCode == REQUEST_CODE_AUTHENTICATION && resultCode == RESULT_OK) {
        startSyncingCommunications(true);
    }/* w  w w. ja  v  a2  s  .  co  m*/

    if (requestCode == Crop.REQUEST_CROP && resultCode == RESULT_OK) {
        Uri output = Crop.getOutput(intent);
        startUpdateAvatar(output.getPath());
    }
}

From source file:com.anhubo.anhubo.ui.activity.unitDetial.UploadingActivity1.java

@TargetApi(19)
private Bitmap handleImageOnKitKat(Intent data) {
    String imagePath = null;/*  ww  w  .  j a  va2 s .c om*/
    Uri uri = data.getData();
    Log.d("TAG", "handleImageOnKitKat: uri is " + uri);
    if (DocumentsContract.isDocumentUri(this, uri)) {
        // documentUridocument id?
        String docId = DocumentsContract.getDocumentId(uri);
        if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
            String id = docId.split(":")[1]; // ??id
            String selection = MediaStore.Images.Media._ID + "=" + id;
            imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
        } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
            Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(docId));
            imagePath = getImagePath(contentUri, null);
        }
    } else if ("content".equalsIgnoreCase(uri.getScheme())) {
        // contentUri??
        imagePath = getImagePath(uri, null);
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        // fileUri???
        imagePath = uri.getPath();
    }
    Bitmap bitmap = displayImage(imagePath);// ?
    return bitmap;
}