简体   繁体   中英

Get directory path from content URI

I'm using the SDK's ACTION_OPEN_DOCUMENT_TREE intent to let the user select a directory. Here's the code:

private static final int REQUEST_PICK_FOLDER = 1;

// …

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_add_folder: {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
            startActivityForResult(intent, REQUEST_PICK_FOLDER);
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_PICK_FOLDER && resultCode == Activity.RESULT_OK) {
        addFolder(data.getData());
    }
}

private void addFolder(Uri uri) {
    Uri docUri = DocumentsContract.buildDocumentUriUsingTree(uri, DocumentsContract.getTreeDocumentId(uri));
    Log.d(TAG, "Folder added: " + docUri.toString());
}

I have an URI (probably) pointing to the folder I just selected. Here's an example output: Folder added: content://com.android.externalstorage.documents/tree/FF30-E80D%3AImages/document/FF30-E80D%3AImages .

Now, I need to get the absolute path, something translating in this case to /storage/sdcard1/Images . I found some code in aFileChooser which seems to work, but not for SD cards, which is my main use case.

I could probably split the URI on %3A , if the preceding part is "primary", then use the first external storage path, if it's something else, use the second one, but it feels wrong… There's probably a more deterministic way to achieve this?

Edit: here's some background on this. I don't need the path to manage the files. But how to present this to the user? I definitely can't show him content://com.android.externalstorage.documents/tree/FF30-E80D%3AImages/document/FF30-E80D%3AImages , that's just scary.

Now, I need to get the absolute path, something translating in this case to /storage/sdcard1/Images.

That is not possible. There is no requirement that the Uri point to a file at all, let alone a file that you can access.

Use a ContentResolver and openInputStream() to get an InputStream on the content and read it in that way. This is not significantly different than how you would handle a URL to a Web server (use HttpUrlConnection to get an InputStream on the Web page or other content).

But how to present this to the user?

I don't know what "this" is. However, you can get the suggested display name associated with the content .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM