0

Using SAF I create a file in the file provider. In onActivityResult I then persist the permissions to that file and store the Uri into the shared preferences. Later I write data into the file.

This seems to work. except if the file was deleted/moved/renamed or basically if it no longer exists.

I can check whether it exists or not using:

val file = DocumentFile.fromSingleUri(applicationContext, uri)
if (!file!!.exists())

But this doesn't solve the problem that I can not write my data using contentResolver.openOutputStream(uri), for I get a FileNotFoundException.

Is there a way to create the file using the stored Uri, while I should still have the permissions persisted?

Guiorgy
  • 1,405
  • 9
  • 26
  • "while I should still have the permissions persisted?" -- I'm not certain that is true, if the content no longer exists. You may need to go through `ACTION_CREATE_DOCUMENT` again (as I assume that is what you used to get the `Uri` originally). – CommonsWare Mar 13 '20 at 16:02
  • @CommonsWare, I did use `ACTION_CREATE_DOCUMENT` and I persisted the permissions using `contentResolver.takePersistableUriPermission(uri, readWriteFlags)`. I haven't explicitly released them is what I meant, and using SAF to create a new document is exactly what I want to avoid, as I write data in a background service – Guiorgy Mar 13 '20 at 16:08
  • "I haven't explicitly released them is what I meant" -- you are assuming that they still exist, despite the document no longer existing. "as I write data in a background service" -- raise a `Notification` to let your user know that you cannot write anymore due to their changes, and use that to steer the user to create a new document for you to use. – CommonsWare Mar 13 '20 at 16:17
  • @CommonsWare, that's my last resort, but for now the question is, if there's ANY was to avoid that? – Guiorgy Mar 13 '20 at 16:52
  • You might want to update your question with the code that is trying to write the content and the complete stack trace. – CommonsWare Mar 13 '20 at 16:55
  • `openOutputStream` throws `FileNotFoundException` when the file no longer exists. That's all – Guiorgy Mar 13 '20 at 17:14

0 Answers0