Search code examples
androidstorage-access-framework

Get Folder Name from Uri using SAF


I am using SAF where user is allowed to select directory/folder and then i would like to display its name in Textview once selected. I used below code to start intent.

  Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                startActivityForResult(intent, 1);

and below code is for onActivityResult

  if (resultCode == RESULT_OK && requestCode == 1) {
    DocumentFile documentFile = DocumentFile.fromTreeUri(this, uriTree);

            textInfo.append(documentFile .getName() + "\n");

        }

Changed question as per guidance, it is returning foldername now.


Solution

  • Use DocumentFile.fromTreeUri() to get a DocumentFile on the tree Uri that you are getting in onActivityResult(). Then, call getName() on the DocumentFile to get a display name associated with that tree.