After a button click, I want to create an Intent for browsing files and selecting a directory. Then I want to store a path for this directory in shared preferences. Later I want to use this path as an argument for a File object, so I can, for example, get a parent directory of a directory I picked, or list all its files. The problem is, I am getting this path from Intent:
content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata
I read here link and tried to convert content Uri to File Uri using cursor, but i am getting this error:
java.lang.UnsupportedOperationException: Unsupported Uri content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata Is it because of characters before "Android" and "data" folder ? It always fails when trying to create a cursor.
Here is a simple example of what I want to achieve. I did not include a code for converting Content Uri to File Uri. I tried almost every code for this what I found, but with no result.
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button.setOnClickListener { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE) startActivityForResult(intent, SELECT_DIRECTORY) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode == Activity.RESULT_OK) { if (requestCode == SELECT_DIRECTORY) { val path = data?.data // convert content Uri to File Uri ? // store path in shared preferences... // later use it in File File(storedPath) } } }
Intentfor this. "The problem is, I am getting this path from Intent" -- that is not a path. That is a string representation of aUri. Specifically, it is aUripointing to a document tree, aUrithat you obtained via the Storage Access Framework. That document tree can be anywhere (e.g., Google Drive, Windows file server); it does not have to represent a directory on an on-device filesystem that you can access.takePersistableUriPermission(). Or, if you insist that you are only willing to work with filesystem directories, stop usingACTION_OPEN_DOCUMENT_TREEand use a directory chooser library.