Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ACTION_OPEN_DOCUMENT_TREE and uri serialization

I'm having trouble with implementing "choose save directory" (for all files) feature in my app (in android 5+). What I need is a directory picker - so I decided to use the system one - with sending intent ACTION_OPEN_DOCUMENT_TREE. What have I done already is to implement all the stuff connected with handling the uri later on, while saving file (creating DocumentFile, creating appropriate Stream, even getting a proper path to be used later). What I cannot achieve is saving the URI I receive (for example in SharedPreferences) to make it more permanent, as it makes one of the app settings, that user has to set once.

This is how I tried to save and restore my uri:

private Uri getSaveTreeUri() {
    if (mSaveTreeUri == null) {
        String uriString = PreferenceManager.getDefaultSharedPreferences(this).getString(SAVE_TREE_URI, null);
        if (uriString != null) mSaveTreeUri = Uri.parse(uriString);
    }
    return mSaveTreeUri;
}

private void setSaveTreeUri(Uri saveTreeUri) {
    mSaveTreeUri = saveTreeUri;
    SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
    editor.putString(SAVE_TREE_URI, saveTreeUri.toString()).commit();
}

And then when I use it, by

DocumentFile documentFileDir = DocumentFile.fromTreeUri(this, getSaveTreeUri());

I get

java.lang.IllegalArgumentException: Invalid URI: /tree/D428-E753:Music

Is there any possibility to make this work? Thanks a lot for all help!

like image 834
Kasia Avatar asked Mar 12 '23 08:03

Kasia


1 Answers

ACTION_OPEN_DOCUMENT_TREE returns a tree Uri that has associated permissions. The permissions must be persisted if in a later session you want to revisit the Uri.

Use takePersistableUriPermission to persist the permissions.

Use getPersistedUriPermissions to get a list of persisted Uris.

like image 88
Peter Tran Avatar answered Mar 24 '23 05:03

Peter Tran