'let user choose a file and open it later

I want to let the user choose a file using

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/json");
startActivityForResult(intent, 1);

and then somehow save the path to this file, so that i can open it anytime.

I tried saving the uri string but when i want to access the file with that later, i get an permission denial exception. I also tried using uri.getPath() to create a File instance, but that didn't work either. Can anyone help me?



Solution 1:[1]

In onActivityResult you should take persistable uri permission in order to use the saved uri.toString() later.

Permissions in manifest are not needed.

Solution 2:[2]

Make sure your Manifest contains the permissions required for accessing storage. Then ask the user to give you the permission using alertDialog and this code

String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, 10);

Then check like that

ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED

for every permission, you ask, every time you use the storage. Now you might be able to access the storage.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 blackapps
Solution 2 shaked428