How to set image from download directory automatically?
I know image name and location, but I dont know what URI should be.
smg like that:
getImageUri(String imageName){
Uri uri = Uri.parse("/download/1A258.png");
imageView.setImageURI(uri);
}
I assume your intention is to access png file in the shared Android Download folder.
Your Uri.parse("/download/1A258.png") resolves to the file path /download/1A258.png at the root of the filesystem, which doesn't exist on Android devices. On many devices, the primary shared Downloads directory is typically under /storage/emulated/0/Download/. Another problem is that on android 10+ direct file access is restricted by scoped storage. Accessing files from it depends on who put the file in this directory, if it was your app then you can get it using MediaStore.Downloads, if some other app (like Chrome,...) then you should use Storage Access Framework.
Your app stored file in downloads folder (using MediaStore or DownloadManager), then access it using MediaStore - no special permissions required:
private void setImageFromDownloads(String imageName) {
String[] projection = { MediaStore.Downloads._ID };
String selection = MediaStore.Downloads.DISPLAY_NAME + " = ?";
String[] selectionArgs = { imageName };
try (Cursor cursor = getContentResolver().query(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
projection,
selection,
selectionArgs,
null)) {
if (cursor != null && cursor.moveToFirst()) {
long id = cursor.getLong(
cursor.getColumnIndexOrThrow(MediaStore.Downloads._ID));
// give you : content://media/external/downloads/<id>
Uri contentUri = ContentUris.withAppendedId(
MediaStore.Downloads.EXTERNAL_CONTENT_URI, id);
imageView.setImageURI(contentUri);
}
} }
If some other app stored file in downloads folder, then you should use SAF. You can read on it in here: https://developer.android.com/training/data-storage/shared/media#saf-other-apps-downloads:
> If your app wants to access a file within the MediaStore.Downloads collection that your app didn't create, you must use the Storage Access Framework.
Handle result:
private final ActivityResultLauncher<Intent> pickImageLauncher =
registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK && result.getData() != null) {
Uri uri = result.getData().getData();
imageView.setImageURI(uri);
}
});
launch file picker with:
private void pickImageFromDownloads() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
pickImageLauncher.launch(intent);
}
marcinj