I am having a problem with selecting image file from external storage using file picker in Android. This question is the consequence of this question - No such file or diectory error in image file upload using Retrofit in Android. What my problem is opening and reading file from external storage on activity result. I want to convert result URI into File.
I read a pdf file from download folder on activity result
Uri bookUri = data.getData();
String filePath = bookUri.toString();//bookUri.toString()
String mime = app.getMimeType(filePath);
if(mime!=null && !mime.isEmpty() && (mime.toLowerCase()=="application/pdf" || mime.toLowerCase()=="application/txt" || mime.toLowerCase()=="application/text"))
bookFile = new File(bookUri.getPath());
Toast.makeText(getBaseContext(),"Unable to process file you have chosen.",Toast.LENGTH_SHORT).show();
Uri selectedImageUri = data.getData();
bmpCoverImage = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
imageFile = new File(selectedImageUri.getPath());
catch (IOException e)
Toast.makeText(getBaseContext(),"An error occurred with the file selected",Toast.LENGTH_SHORT).show();
imageFile = new File(Environment.getExternalStorageDirectory(),selectedImageUri.getPath());
I am having a problem with selecting image file from external storage using file picker in Android
If you are referring to the code that you are using in this question, you are not "using file picker". You are using
ACTION_GET_CONTENT, which has never been a "file picker", nor will it ever be a "file picker".
I want to convert result URI into File.
Usually, that is not necessary. But, if that is what you want to do:
openInputStream() to get an
InputStream on the content represented by the
FileOutputStream on your desired file
use Java I/O to copy the bytes from the
InputStream into the
The above code works well. It is working.
It works for the small number of devices that you tested, for the specific activities that the user chose to handle the
ACTION_GET_CONTENT request. It will not work on most Android devices, and it will not work in most circumstances. The only time that code will work is if the
Uri has a
file scheme. Most of the time, it will not. Instead, it will have a
content scheme, representing content supplied by a
Please how can I open the image file correctly from external storage?
If you wish to continue using
ACTION_GET_CONTENT, please understand that this has nothing to do with external storage specifically. You are not getting a file, on external storage or elsewhere. You are getting a
Uri. This is akin to a URL, such as the URL for this Web page. Just as a URL does not necessarily point to a file on your hard drive, a
Uri does not necessarily point to a file on the filesystem. Use a
DocumentFile to work with the
Uri and the content that it identifies.
If you want to always get files on external storage (and nowhere else), then use an actual file picker library.