'Retrieving image in scoped storage Android 11
I'm working on scanner app. My problem is while retrieve saved image from scoped storage in Android 10 and 11. Image is saved successfully but I am not able to retrieve it. When I get path of save image bitmap is null.
Here is the code to save the image in Android 11:
File dirDest = new File(Environment.DIRECTORY_PICTURES, context.getString(R.string.app_name));
Long date = System.currentTimeMillis();
String extension = ".jpg";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, date + extension);
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/" + extension);
contentValues.put(MediaStore.Images.Media.DATE_ADDED, date);
contentValues.put(MediaStore.Images.Media.DATE_MODIFIED, date);
contentValues.put(MediaStore.Images.Media.SIZE, bitmap.getByteCount());
contentValues.put(MediaStore.Images.Media.WIDTH, bitmap.getWidth());
contentValues.put(MediaStore.Images.Media.HEIGHT, bitmap.getHeight());
contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, dirDest + File.separator);
Uri newImageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
FileOutputStream fos = (FileOutputStream) resolver.openOutputStream(Objects.requireNonNull(newImageUri));
callback.write(fos);
fos.flush();
fos.close();
return String.valueOf(dirDest) + date + extension;
Here is the code to retrieve the save image from shared storage in scoped storage in Android 11. I am getting issue in this part of code, bitmap is null. I am not getting the main point of the problem. In the end the problem is FileNotFoundException.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
String[] file = {MediaStore.Images.Media._ID,
MediaStore.Images.Media.RELATIVE_PATH,
MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.SIZE,
MediaStore.Images.Media.MIME_TYPE,
MediaStore.Images.Media.WIDTH,
MediaStore.Images.Media.HEIGHT,
MediaStore.Images.Media.DATE_MODIFIED};
if (uri != null) {
cursor = context.getContentResolver().query(uri, file, null, null, null);
if (cursor != null) {
try {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(file[0]);
File path = new File(uri.getPath());
bitmap = BitmapFactory.decodeFile(path.getAbsolutePath());
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Solution 1:[1]
You can query them all with the help of SimpleStorage:
val images: List<MediaFile> = MediaStoreCompat.fromMediaType(applicationContext, MediaType.IMAGE)
images.forEach {
println(it.absolutePath)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anggrayudi H |
