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:com.fbartnitzek.tasteemall.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.v(LOG_TAG, "onActivityResult, hashCode=" + this.hashCode() + ", " + "requestCode = [" + requestCode
            + "], resultCode = [" + resultCode + "], data = [" + data + "]");

    if (requestCode == REQUEST_EXPORT_DIR_CODE
            || requestCode == REQUEST_IMPORT_FILES_CODE && resultCode == AppCompatActivity.RESULT_OK) {
        Uri uri;
        if (data.getBooleanExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false)) {

            List<File> files = new ArrayList<>();
            // For JellyBean and above
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                ClipData clip = data.getClipData();

                if (clip != null) {
                    for (int i = 0; i < clip.getItemCount(); i++) {
                        uri = clip.getItemAt(i).getUri();
                        //                            Log.v(LOG_TAG, "onActivityResult, uri=" + uri + ", hashCode=" + this.hashCode() + ", " + "requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]");
                        files.add(new File(uri.getPath()));
                        // Do something with the URI
                    }//from   w  w  w .j  a va 2 s.  co m
                }
                // For Ice Cream Sandwich
            } else {
                ArrayList<String> paths = data.getStringArrayListExtra(FilePickerActivity.EXTRA_PATHS);

                if (paths != null) {
                    for (String path : paths) {
                        uri = Uri.parse(path); // TODO: might be useless conversion...
                        //                            Log.v(LOG_TAG, "onActivityResult, uri=" + uri + ", hashCode=" + this.hashCode() + ", " + "requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]");
                        files.add(new File(uri.getPath()));
                    }
                }
            }

            if (!files.isEmpty() && requestCode == REQUEST_IMPORT_FILES_CODE) {

                // TODO: refactor afterwards without mFiles
                // new ImportFilesTask(MPA.this, MPA.this).execute(files.toArray(new File[files.size()]));

                mFiles = files;
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("which import shall be used?")
                        .setPositiveButton("class-based", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                new ImportFilesTask(MainActivity.this, MainActivity.this)
                                        .execute(mFiles.toArray(new File[mFiles.size()]));
                                mFiles = null;
                            }
                        })
                        //                            .setNegativeButton("old", new DialogInterface.OnClickListener() {
                        //                                @Override
                        //                                public void onClick(DialogInterface dialog, int which) {
                        //                                    new ImportFilesOldFormatTask(MainActivity.this, MainActivity.this)
                        //                                            .execute(mFiles.toArray(new File[mFiles.size()]));
                        //                                    mFiles = null;
                        //                                }
                        //                            });
                        .setNegativeButton("all-in-1", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                // multiple all-in-1-files?
                                new ImportAllInOneFileTask(MainActivity.this, MainActivity.this)
                                        .execute(mFiles.get(0));
                                mFiles = null;
                                // to get all easier:
                                // either all ids are known or lots of parallel stuff...
                                // dialog with warning!
                                // task won't help => needs Dialog everywhere... => Task
                                // merge is to complicated for now :-p

                            }
                        });
                builder.show();
            }

        } else {
            //                Log.v(LOG_TAG, "onActivityResult - single file, hashCode=" + this.hashCode() + ", " + "requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]");
            uri = data.getData();
            // Do something with the URI
            if (uri != null && requestCode == REQUEST_EXPORT_DIR_CODE) {
                //somehow it returned a filepath (confusing use of multiple flag...
                new ExportToDirTask(this, this).execute(new File(uri.getPath()));
            }

        }

    } else if (requestCode == REQUEST_EDIT_PRODUCER_GEOCODE && resultCode == AppCompatActivity.RESULT_OK) {

        if (mProducerLocationUris == null) {
            Log.e(LOG_TAG, "onActivityResult mProducerLocationUris == null! - should never happen...");
            return;
        }

        if (mProducerLocationUris.isEmpty()) {
            if (mReviewLocationUris != null && !mReviewLocationUris.isEmpty()) {
                showReviewLocationGeocodeDialog(true);
            } else {
                Toast.makeText(MainActivity.this, "all geocoding done", Toast.LENGTH_SHORT).show();
                restartCurrentFragmentLoader();
            }
        } else {
            showProducerGeocodeDialog(true);
        }

    } else if (requestCode == REQUEST_EDIT_REVIEW_LOCATION_GEOCODE
            && resultCode == AppCompatActivity.RESULT_OK) {
        if (mReviewLocationUris == null) {
            Log.e(LOG_TAG, "onActivityResult mReviewLocationUris == null! - should never happen");
            return;
        }

        if (mReviewLocationUris.isEmpty()) {
            Toast.makeText(MainActivity.this, "all geocoding done", Toast.LENGTH_SHORT).show();
            restartCurrentFragmentLoader();
        } else {
            showReviewLocationGeocodeDialog(true);
        }
    } else if (requestCode == ADD_REVIEW_REQUEST && resultCode == Activity.RESULT_OK && data != null) {
        // TODO bugfix: refresh current pager
        startActivity(new Intent(this, ShowReviewActivity.class).setData(data.getData()));
    }

    super.onActivityResult(requestCode, resultCode, data);
}

From source file:com.owncloud.android.ui.activity.FileDisplayActivity.java

private void requestSimpleUpload(Intent data, int resultCode) {
    String filepath = null;/*from  www. ja v a 2 s.  com*/
    try {
        Uri selectedImageUri = data.getData();

        String filemanagerstring = selectedImageUri.getPath();
        String selectedImagePath = getPath(selectedImageUri);

        if (selectedImagePath != null)
            filepath = selectedImagePath;
        else
            filepath = filemanagerstring;

    } catch (Exception e) {
        Log_OC.e(TAG, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
        e.printStackTrace();

    } finally {
        if (filepath == null) {
            Log_OC.e(TAG, "Couldnt resolve path to file");
            Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content),
                    Toast.LENGTH_LONG);
            t.show();
            return;
        }
    }

    Intent i = new Intent(this, FileUploader.class);
    i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
    String remotepath = new String();
    for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
        remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
    }
    if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
        remotepath += OCFile.PATH_SEPARATOR;
    remotepath += new File(filepath).getName();

    i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
    i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
    i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
    if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
        i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
    startService(i);
}

From source file:com.intel.xdk.camera.Camera.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.//from   ww  w  .  j a va 2  s .  c  o  m
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @author paulburke
 */
@SuppressLint("NewApi")
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];
            }

            // 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.packageinstaller.PackageInstallerActivity.java

private void processPackageUri(final Uri packageUri) {
    mPackageURI = packageUri;//from  ww w.ja  v  a 2 s .co  m

    final String scheme = packageUri.getScheme();
    final PackageUtil.AppSnippet as;

    switch (scheme) {
    case SCHEME_PACKAGE: {
        try {
            mPkgInfo = mPm.getPackageInfo(packageUri.getSchemeSpecificPart(),
                    PackageManager.GET_PERMISSIONS | PackageManager.GET_UNINSTALLED_PACKAGES);
        } catch (NameNotFoundException e) {
        }
        if (mPkgInfo == null) {
            Log.w(TAG, "Requested package " + packageUri.getScheme()
                    + " not available. Discontinuing installation");
            showDialogInner(DLG_PACKAGE_ERROR);
            setPmResult(PackageManager.INSTALL_FAILED_INVALID_APK);
            return;
        }
        as = new PackageUtil.AppSnippet(mPm.getApplicationLabel(mPkgInfo.applicationInfo),
                mPm.getApplicationIcon(mPkgInfo.applicationInfo));
    }
        break;

    case SCHEME_FILE: {
        File sourceFile = new File(packageUri.getPath());
        PackageParser.Package parsed = PackageUtil.getPackageInfo(sourceFile);

        // Check for parse errors
        if (parsed == null) {
            Log.w(TAG, "Parse error when parsing manifest. Discontinuing installation");
            showDialogInner(DLG_PACKAGE_ERROR);
            setPmResult(PackageManager.INSTALL_FAILED_INVALID_APK);
            return;
        }
        mPkgInfo = PackageParser.generatePackageInfo(parsed, null, PackageManager.GET_PERMISSIONS, 0, 0, null,
                new PackageUserState());
        as = PackageUtil.getAppSnippet(this, mPkgInfo.applicationInfo, sourceFile);
    }
        break;

    case SCHEME_CONTENT: {
        mStagingAsynTask = new StagingAsyncTask();
        mStagingAsynTask.execute(packageUri);
        return;
    }

    default: {
        Log.w(TAG, "Unsupported scheme " + scheme);
        setPmResult(PackageManager.INSTALL_FAILED_INVALID_URI);
        clearCachedApkIfNeededAndFinish();
        return;
    }
    }

    PackageUtil.initSnippetForNewApp(this, as, R.id.app_snippet);

    initiateInstall();
}

From source file:com.aimfire.gallery.cardboard.PhotoActivity.java

private String getFilePathFromUri(Uri uri) {
    String filePath = null;/*  w w w .  j a v  a 2 s . c  om*/
    if ("content".equals(uri.getScheme())) {
        return null;

        /*
                    String[] filePathColumn = { MediaColumns.DATA };
                    ContentResolver contentResolver = getContentResolver();
                
                    Cursor cursor = contentResolver.query(uri, filePathColumn, null,
            null, null);
                
                    cursor.moveToFirst();
                
                    //int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
                    filePath = cursor.getString(columnIndex);
                    cursor.close();
        */
    } else if ("file".equals(uri.getScheme())) {
        filePath = new File(uri.getPath()).getAbsolutePath();
    }
    return filePath;
}

From source file:com.deliciousdroid.activity.BrowseBookmarks.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.browse_bookmarks);

    Intent intent = getIntent();/*from  w w  w .j ava2s.  c om*/

    Uri data = intent.getData();
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction t = fm.beginTransaction();

    Fragment bookmarkFrag;

    if (fm.findFragmentById(R.id.listcontent) == null) {
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            Bundle searchData = intent.getBundleExtra(SearchManager.APP_DATA);

            if (searchData != null) {
                tagname = searchData.getString("tagname");
                username = searchData.getString("username");
                unread = searchData.getBoolean("unread");
            }

            query = intent.getStringExtra(SearchManager.QUERY);

            if (intent.hasExtra("username")) {
                username = intent.getStringExtra("username");
            }

            if (data != null && data.getUserInfo() != null) {
                username = data.getUserInfo();
            }
        } else {
            if (data != null) {
                if (data.getUserInfo() != "") {
                    username = data.getUserInfo();
                } else
                    username = mAccount.name;
                tagname = data.getQueryParameter("tagname");
                unread = data.getQueryParameter("unread") != null;
                path = data.getPath();
            }
        }

        if (isMyself()) {
            bookmarkFrag = new BrowseBookmarksFragment();
        } else {
            bookmarkFrag = new BrowseBookmarkFeedFragment();
        }

        t.add(R.id.listcontent, bookmarkFrag);
    } else {
        if (savedInstanceState != null) {
            username = savedInstanceState.getString(STATE_USERNAME);
            tagname = savedInstanceState.getString(STATE_TAGNAME);
            unread = savedInstanceState.getBoolean(STATE_UNREAD);
            query = savedInstanceState.getString(STATE_QUERY);
            path = savedInstanceState.getString(STATE_PATH);
        }

        bookmarkFrag = fm.findFragmentById(R.id.listcontent);
    }

    if (isMyself()) {
        if (query != null && !query.equals("")) {
            ((BrowseBookmarksFragment) bookmarkFrag).setSearchQuery(query, username, tagname, unread);
        } else {
            ((BrowseBookmarksFragment) bookmarkFrag).setQuery(username, tagname, unread);
        }
    } else {
        if (query != null && !query.equals("")) {
            ((BrowseBookmarkFeedFragment) bookmarkFrag).setQuery(username, tagname);
        } else {
            ((BrowseBookmarkFeedFragment) bookmarkFrag).setQuery(username, query);
        }
    }

    BrowseTagsFragment tagFrag = (BrowseTagsFragment) fm.findFragmentById(R.id.tagcontent);
    if (tagFrag != null) {
        tagFrag.setAccount(username);
    }

    if (path != null && path.contains("tags")) {
        t.hide(fm.findFragmentById(R.id.maincontent));
        findViewById(R.id.panel_collapse_button).setVisibility(View.GONE);
    } else {
        if (tagFrag != null) {
            t.hide(tagFrag);
        }
    }

    Fragment addFrag = fm.findFragmentById(R.id.addcontent);
    if (addFrag != null) {
        t.hide(addFrag);
    }

    t.commit();
}

From source file:Main.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./*from  w w  w.jav a2s . co m*/
 *
 * @param context The context.
 * @param uri The Uri to query.
 */
public static String getPath(final Context context, final Uri uri) {

    // DocumentProvider
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT // is Kitkat or later
            && 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];
            }

        }
        // 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);
        }
        // DriveDocument
        else if (isDriveDocument(uri)) {
            // I have not found a way to generate the absolute url.
            // Check from outside if it's a GoogleDrive document.
            // Generate a bitmap and convert to bytes.
            return null;
        }
    }
    // 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:com.pindroid.activity.BrowseBookmarks.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.browse_bookmarks);

    Intent intent = getIntent();/*from  w w w . ja v a2  s  . c  om*/

    Uri data = intent.getData();
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction t = fm.beginTransaction();

    if (fm.findFragmentById(R.id.listcontent) == null) {
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            Bundle searchData = intent.getBundleExtra(SearchManager.APP_DATA);

            if (searchData != null) {
                tagname = searchData.getString("tagname");
                app.setUsername(searchData.getString("username"));
                unread = searchData.getBoolean("unread");
            }

            query = intent.getStringExtra(SearchManager.QUERY);

            if (intent.hasExtra("username")) {
                app.setUsername(intent.getStringExtra("username"));
            }

            if (data != null) {
                feed = data.getQueryParameter("feed");

                if (data.getUserInfo() != null) {
                    app.setUsername(data.getUserInfo());
                }
            }
        } else {
            if (data != null) {
                tagname = data.getQueryParameter("tagname");
                feed = data.getQueryParameter("feed");
                unread = data.getQueryParameter("unread") != null;
                path = data.getPath();
            }
        }

        if (feed == null || feed.equals("")) {
            bookmarkFrag = new BrowseBookmarksFragment();
        } else {
            bookmarkFrag = new BrowseBookmarkFeedFragment();
        }

        t.add(R.id.listcontent, bookmarkFrag);
    } else {
        if (savedInstanceState != null) {
            tagname = savedInstanceState.getString(STATE_TAGNAME);
            unread = savedInstanceState.getBoolean(STATE_UNREAD);
            query = savedInstanceState.getString(STATE_QUERY);
            path = savedInstanceState.getString(STATE_PATH);
            feed = savedInstanceState.getString(STATE_FEED);
        }

        bookmarkFrag = fm.findFragmentById(R.id.listcontent);
    }

    if (feed == null || feed.equals("")) {
        if (query != null && !query.equals("")) {
            ((BrowseBookmarksFragment) bookmarkFrag).setSearchQuery(query, app.getUsername(), tagname, unread);
        } else {
            ((BookmarkBrowser) bookmarkFrag).setQuery(app.getUsername(), tagname, unread ? "unread" : null);
        }

        ((BrowseBookmarksFragment) bookmarkFrag).refresh();
    } else {
        if (query == null || query.equals("")) {
            ((BookmarkBrowser) bookmarkFrag).setQuery(app.getUsername(), tagname, feed);
        } else {
            ((BookmarkBrowser) bookmarkFrag).setQuery(app.getUsername(), query, feed);
        }
    }

    BrowseTagsFragment tagFrag = (BrowseTagsFragment) fm.findFragmentById(R.id.tagcontent);

    if (tagFrag != null) {
        tagFrag.setAccount(app.getUsername());
    }

    if (path != null && path.contains("tags")) {
        t.hide(fm.findFragmentById(R.id.maincontent));
        findViewById(R.id.panel_collapse_button).setVisibility(View.GONE);
    } else {
        if (tagFrag != null) {
            t.hide(tagFrag);
        }
    }

    Fragment addFrag = fm.findFragmentById(R.id.addcontent);
    if (addFrag != null) {
        t.hide(addFrag);
    }

    t.commit();
}

From source file:com.popcorntime.apps.remote.utils.Utils.java

public static String getRealPathFromUri(Context context, Uri contentUri) {
    Log.i("uri", contentUri.toString());
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        Cursor cursor = null;//from  w w  w. ja  va 2 s  .  c om
        try {

            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    } else {
        Uri uri = contentUri;
        // DocumentProvider
        if (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 contentUri2 = ContentUris
                        .withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

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

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

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

                return getDataColumn(context, contentUri2, 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.amytech.android.library.views.imagechooser.threads.MediaProcessorThread.java

@TargetApi(Build.VERSION_CODES.KITKAT)
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];
            }// w  w w  .  j  av a  2 s  .c  o 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;
}