AndreaF
AndreaF

Reputation: 12385

How to get access to a directory and its files from tree URI path with SAF

I want to pick all files in a directory and then store as copy compressed version of these files in the same directory.

If I use Intent.ACTION_OPEN_DOCUMENT_TREE I get a tree Uri, but I cannot figure how I could get the file Uri of all files contained in it and how to write in the directory itself.

In the documentation I cannot find any similar use case.

Before forced SAF it was enough to get directory path and work with standard File methods, unfortunately now all the past methods based on Files and explicit paths are broken with this SAF.

Upvotes: 2

Views: 3116

Answers (2)

Simon
Simon

Reputation: 2066

It tooks me a while to figure out:

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
private List<Uri> readFiles(Context context, Intent intent) {
    List<Uri> uriList = new ArrayList<>();

    // the uri returned by Intent.ACTION_OPEN_DOCUMENT_TREE
    Uri uriTree = intent.getData();
    // the uri from which we query the files
    Uri uriFolder = DocumentsContract.buildChildDocumentsUriUsingTree(uriTree, DocumentsContract.getTreeDocumentId(uriTree));

    Cursor cursor = null;
    try {
        // let's query the files
        cursor = context.getContentResolver().query(uriFolder,
                new String[]{DocumentsContract.Document.COLUMN_DOCUMENT_ID},
                null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            do {
                // build the uri for the file
                Uri uriFile = DocumentsContract.buildDocumentUriUsingTree(uriTree, cursor.getString(0));
                //add to the list
                uriList.add(uriFile);

            } while (cursor.moveToNext());
        }

    } catch (Exception e) {
        // TODO: handle error
    } finally {
        if (cursor!=null) cursor.close();
    }

    //return the list
    return uriList;
}

Upvotes: 3

CommonsWare
CommonsWare

Reputation: 1006674

I cannot figure how I could get the file Uri of all files contained in it and how to write in the directory itself.

Use DocumentFile.fromTreeUri() to get a DocumentFile from the Uri that you get back from ACTION_OPEN_DOCUMENT_TREE. You can then use methods on DocumentFile to list the "files" in the "directory", plus createFile() to create a new document ("file") in the tree.

Upvotes: 2

Related Questions