Home > other >  let user choose a file and open it later
let user choose a file and open it later

Time:03-01

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?

CodePudding user response:

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

Permissions in manifest are not needed.

CodePudding user response:

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.

  • Related