0

I'm trying to save a text file using SAF (Storage Access Framework) but I can't control where it should be saved, I used this method from the Documentation as follows:

private void createFile(Uri pickerInitialUri) {
    Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("text/*");
    intent.putExtra(Intent.EXTRA_TITLE, "new.txt");

    // Optionally, specify a URI for the directory that should be opened in
    // the system file picker when your app creates the document.
    intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);


    startActivityForResult(intent, CREATE_FILE);
}

Passing the root directory Uri as follows:

Uri.parse(Environment.getExternalStorageDirectory().toString())

But whatever string I parse and even if I pass null as Uri, the framework UI always starts in Downloads.

I want to save the file in the root directory. also, I want to save it automatically without any user interaction.

mahmoudsfares
  • 33
  • 1
  • 9
  • Use an uri you obtained earlier picking a drectory or file. You cannot make those uries yourself. – blackapps Nov 25 '20 at 09:21
  • You cannot save using SAF without at least once a user interaction. – blackapps Nov 25 '20 at 09:30
  • @blackapps you mean that I should get the uri from logs or via debugger from onActivityResult? I can't quite understand what you mean by the uri I obtained earlier – mahmoudsfares Nov 25 '20 at 10:57
  • @balckapps the starting directory is always where I saved the last time.. if it's the first time the starting directory is downloads as I mentioned in the question – mahmoudsfares Nov 25 '20 at 11:10
  • `the starting directory is always where I saved the last time.` Yes if you do nothing. Reread my first comment. – blackapps Nov 25 '20 at 11:31

1 Answers1

0

Quoting the documentation for EXTRA_INITIAL_URI:

[The extra] should specify a document URI or a tree URI with document ID.

A "document URI" is one that you obtained previously from ACTION_OPEN_DOCUMENT or ACTION_CREATE_DOCUMENT. A "tree URI" is one that you obtained previously from ACTION_OPEN_DOCUMENT_TREE. Uri.parse() is neither of those.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thanks for the clarification, turns out that SAF is not suitable for my use case.. I want to verify a device by saving a text file with the serial in a directory other than the app's directory, because I want this file safe if the user uninstalled and re-installed the app.. SAF won't be suitable as this file is read on login and the user isn't supposed to navigate every login to that directory.. any suggestions on how we can do that? – mahmoudsfares Nov 26 '20 at 12:34
  • @mahmoudsfares: Sorry, but what you are looking for is not really a supported pattern on modern versions of Android. – CommonsWare Nov 26 '20 at 13:13