Till now, I check whether a file exists or not and if it does not then I save it to the device in Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) but it is not supported from Android 10.
So I tried to use mediastore API for saving the image.
READ_STORAGE_PERMISSION -> NOT ALLOWED
First I query the contentresolver to check the existence of the file with the following code:
Uri collection = null;
collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
String[] PROJECTION = new String[]{MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.MediaColumns.RELATIVE_PATH};
String QUERY = MediaStore.Files.FileColumns.RELATIVE_PATH + " like ? and " +
MediaStore.Files.FileColumns.DISPLAY_NAME + " like ?";
ContentResolver mContentResolver = this.getContentResolver();
Cursor cursor = mContentResolver.query(collection, PROJECTION, QUERY , new String[]{"%" + dirName + "%", "%" + fname + "%"}, null);
if (cursor != null) {
Log.d("upisdk", "cursor != null");
if (cursor.getCount() > 0) {
} else {
}
}
If the cursor is empty, then it means that the file does not exists and I will save the file using code
ContentResolver contentResolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fname);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, dirName);
Uri imageUri =
contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
fos = contentResolver.openOutputStream(Objects.requireNonNull(imageUri));
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Objects.requireNonNull(fos).close();
Now If everything is working fine until I delete the App data.
After deleting the data, the folder is still there and the previously saved file also. Now If the query the contentresolver for that file, it is giving cursor empty. If the READ_STORAGE_PERMISSION is not allowed then it is happening. If I allow the READ_STORAGE_PERMISSION then it is giving me the cursor non-empty. On the other hand, If i try to save a new different image and query the resolver then I am getting non-empty cursor even without the READ_STORAGE_PERMISSION.
Please tell me what I am doing wrong.