Home > Software engineering >  Access files using `ACTION_OPEN_DOCUMENT_TREE`
Access files using `ACTION_OPEN_DOCUMENT_TREE`

Time:11-20

i'm trying to access to files inside the folder selected by the but the listFiles() return null always. this my code.

    private void RequestSAFPermission(){
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    startActivityForResult(intent, 101);
}




@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != RESULT_OK)
        return;
    Uri treeUri = data.getData();
    DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
    grantUriPermission(getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    Uri docUri = DocumentsContract.buildDocumentUriUsingTree(treeUri,
            DocumentsContract.getTreeDocumentId(treeUri));
    path = getPath(getBaseContext(), docUri);
    File file = new File(path);
    File[] files = file.listFiles();

}

getPath() is from here

CodePudding user response:

Use pickedDir.listFiles() instead.

  • Related