Reputation: 537
I've got a activity/intent launcher, where the user can choose a directory from the external storage. After choosing a folder, the uri path is stored in sharedpreferences and the foldername is displayed in a textview:
ActivityResultLauncher<Intent> actResLauncher;
actResLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(),this);
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
actResLauncher.launch(intent);
@Override
public void onActivityResult(ActivityResult result) {
int resultCode = result.getResultCode();
Intent resultIntent = result.getData();
if (resultCode == Activity.RESULT_OK && resultIntent != null) {
Uri uri = resultIntent.getData();
//Safe Uri "path" to shared preference
SharedPreferences.Editor editor = getContext().getSharedPreferences(AppConstants.BACKUP, MODE_PRIVATE).edit();
editor.putString(AppConstants.AUTOMATIC_BACKUP_FOLDER, uri.toString());
editor.commit();
//Display Folderdame on textview
DocumentFile documentFile = DocumentFile.fromTreeUri(getContext(), uri);
automaticBackupFolder.setText(documentFile.getName());
)
}
This works like charm and the Uri can be restored from the Shared Preference Folder:
SharedPreferences prefs = getContext().getSharedPreferences(AppConstants.BACKUP, MODE_PRIVATE);
DocumentFile sourceFile = DocumentFile.fromSingleUri(getContext(), Uri.parse(prefs.getString(AppConstants.AUTOMATIC_BACKUP_FOLDER)));
automaticBackupFolder.setText(sourceFile.getName()); //Throws UnsupportedOperationException: Unsupported Uri content exception
Using the DocumentFile
object I can get the parent file, check if folder exsists etc. and that works perfectly.
However, the issue is that when recreating the fragment (e.g by rotating the phone), the function getPath()
throws the following exception: UnsupportedOperationException: Unsupported Uri content
This error does not occur when displaying the Folder Name in the onActivityResult function, it appears when the Uri gets stored in the Shared Preferences Folder AND the fragment is created again (e.g. rotating phone)
What might the issue be? Is it maybe that after recreating the fragment, the app loses permissions to view the folder name?
Upvotes: 1
Views: 1194
Reputation: 1007533
In onActivityResult()
, when you get your Uri
, call takePersistableUriPermission()
on a ContentResolver
, passing in your Uri
. Otherwise, your access to the content is limited to whatever activity instance got the Uri
and goes away entirely when your process is terminated.
Upvotes: 2