Reputation: 17526
I'm building an android app in which I have to read a file from the Downloads
folder of my Motorola G 2015 phone running Android Marshmallow (API v23).
To achieve this I'd like to choose the file via an OPEN_DOCUMENT
or GET_CONTENT
intent to leverage existing file-browsers on the user's phone, rather than implementing my own.
My manifest declares :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I have tried to receive the result from the intent like this:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case action_choose_file:
Intent chooseFile;
Intent intent;
chooseFile = new Intent(Intent.ACTION_OPEN_DOCUMENT);
chooseFile.setType("application/epub+zip");
intent = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
return true;
.....
}
}
To process the result I do this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
String filePath = uri.getPath();
final InputStream in = new FileInputStream(filePath);
}
break;
....
}
}
However new FileInputStream
fails with a ENOENT
- file does not exist exception, and logging filePath
reveals that it's value is something like /documents/2055
rather than the real filepath.
I suspect that I need something like querying DocumentProvider
, but I could not find a case similar to mine.
It's worth mentioning that a couple of years ago my code used to work pretty much like this so I suspect something changed about the way android handles file access.
How do I access a file from the Downloads
location of my android phone?
Upvotes: 1
Views: 1799
Reputation: 1007534
How do I get a file system path from an OPEN_DOCUMENT intent?
You don't. There is no requirement that there be a file for that Uri
, let alone one that you can access.
However new FileInputStream fails with a ENOENT- file does not exist exception, and logging filePath reveals that it's value is something like /documents/2055 rather than the real filepath.
Use a ContentResolver
and openInputStream()
and/or openOutputStream()
to get a stream on the data represented by that Uri
.
How do I access a file from the Downloads location of my android phone?
Either use an existing file-browsing library, or write your own file-browsing UI. The Storage Access Framework (ACTION_OPEN_DOCUMENT
and kin) is for allowing the user to choose the content from where the user has chosen to store it, whether that be in a Downloads/
directory, or Google Drive, or Dropbox, or anywhere else.
Upvotes: 4