So our app has the option to take either a picture or a video. If the user takes a picture, we can use the MediaStore.Images.Media.insertImage function to add the new image (via a filepath) to the phone's gallery and generate a content:// style URI. Is there a similar process for a captured video, given that we only have it's filepath?
Here is an easy 'single file based solution':
Whenever you add a file, let MediaStore Content Provider knows about it using
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageAdded)));
Main advantage: work with any mime type supported by MediaStore
Whenever you delete a file, let MediaStore Content Provider knows about it using
getContentResolver().delete(uri, null, null)
I'm also interested, could you find a solution?
Edit: solution is RTFM. Based on the "Content Providers" chapter here is my code that worked:
// Save the name and description of a video in a ContentValues map.
ContentValues values = new ContentValues(2);
values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
// values.put(MediaStore.Video.Media.DATA, f.getAbsolutePath());
// Add a new record (identified by uri) without the video, but with the values just set.
Uri uri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
// Now get a handle to the file for that record, and save the data into it.
try {
InputStream is = new FileInputStream(f);
OutputStream os = getContentResolver().openOutputStream(uri);
byte[] buffer = new byte[4096]; // tweaking this number may increase performance
int len;
while ((len = is.read(buffer)) != -1){
os.write(buffer, 0, len);
}
os.flush();
is.close();
os.close();
} catch (Exception e) {
Log.e(TAG, "exception while writing video: ", e);
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
If your app is generating a new video and you simply want to give the MediaStore some metadata for it, you can build on this function:
public Uri addVideo(File videoFile) {
ContentValues values = new ContentValues(3);
values.put(MediaStore.Video.Media.TITLE, "My video title");
values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
values.put(MediaStore.Video.Media.DATA, videoFile.getAbsolutePath());
return getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
}
EDIT: As of Android 4.4 (KitKat), this method no longer works.
I was unable to get the Intent.ACTION_MEDIA_SCANNER_SCAN_FILE broadcast to work for me under API 21 (Lollipop), but the MediaScannerConnection does work, e.g.:
MediaScannerConnection.scanFile(
context, new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.d(TAG, "Finished scanning " + path + " New row: " + uri);
}
} );
Try this code. It seems working for me.
filePath = myfile.getAbsolutePath();
ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
Example of filePath -
/storage/emulated/0/DCIM/Camera/VID_20140313_114321.mp4
Related
Hi I am new to android development and have been trying to accomplish the above said functionality.
I am testing app on Android 9, API 28. I am able to save captured image to folder but not been able to display it in gallery (Like WhatsApp).
I have tried:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
OutputStream os;
String[] split = imagePathNew.split("\\.");
ContentResolver resolver = context.getContentResolver();
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, split[0] + ".jpg");
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + File.separator + "Test");
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
os = (OutputStream) resolver.openOutputStream(Objects.requireNonNull(imageUri)); // imageLocalUri is the uri of captured image in folder
Bitmap bitmap = MediaStore.Images.Media.getBitmap(resolver, imageLocalUri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
Objects.requireNonNull(os);
} else {
Intent updateInGallery = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
updateInGallery.setData(imageLocalUri); // imageLocalUri is the uri of captured image in folder
context.sendBroadcast(updateInGallery);
}
Can someone please help me with what am I doing wrong here?
Nothing is wrong with the posted code.
In the addition use following class
https://developer.android.com/reference/android/media/MediaScannerConnection#scanFile(java.lang.String,%20java.lang.String)
From docs
provides a way for applications to pass a newly created or downloaded media file to the media scanner service. The media scanner service will read metadata from the file and add the file to the media content provider.
I'm saving an image in DCIM directory, but in cases, I need to delete it.
Previously, I called just image.delete(), where image is file. But now this image is saved in another way:
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM" + File.separator + IMAGES_FOLDER_NAME);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
OutputStream fos = resolver.openOutputStream(imageUri);
boolean saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
I tried to make a query with its name and call contentResolver.delete(...), but it doesn't work.
I have permission to write external storage, but I don't want to use SAF.
How can I delete such file?
You need to use the delete method of ContentResolver using the Uri you got when you called insert.
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
OutputStream fos = resolver.openOutputStream(imageUri);
boolean saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
......
int result = resolver.delete(imageUri, null, null);
if (result > 0) {
Log.d("Tag", "File deleted");
}
If you didn't store the Uri you need to perform a query(), retrieve the content and then call delete.
intent.addFlags before invoke the method startActivityForResult.
like this
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
Because it check permission in ContentProvider#enforceWritePermissionInner.
The real implement is in ActivityManagerService#checkPermission method.
File file = new File(delPath);
if (file.exists()) {
try {
Uri imageUri = FileProvider.getUriForFile(Context,
getApplicationContext()
.getPackageName() + ".provider", file);
ContentResolver contentResolver = getContentResolver();
int deletefile = contentResolver.delete(imageUri, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
Here delete path delPath is the file path of Image you want to delete from storage.
The complete solution should include also handling the potential errors which will occure on Andorid Q when trying to delete using ContentResolver. In that case, you should wrap your code in the try/catch block.
Below solution:
try {
// 1
getApplication<Application>().contentResolver.delete(
imageUri,"${MediaStore.Images.Media._ID} = ?",
arrayOf(imageId)
)
}
// 2
catch (securityException: SecurityException) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val recoverableSecurityException =
securityException as? RecoverableSecurityException
?: throw securityException
val intentSender = recoverableSecurityException.userAction.actionIntent.intentSender
startIntentSenderForResult(
intentSender,
DELETE_PERMISSION_REQUEST,
null,
0,
0,
0,
null
)
} else {
throw securityException
}
}
Here, you call contentResolver.delete() inside a try block since this method can throw a SecurityException at runtime. The method requires the ContentUri of the image you want to delete. In the where parameter, you specify that you want to delete an image based on its _ID. In the final parameter, you pass the string version of the _ID in an array.
In Android 10 and above, it isn’t possible to delete or modify items from MediaStore directly. You need permission for these actions. The correct approach is to first catch RecoverableSecurityException, which contains an intentSender that can prompt the user to grant permission. You then startIntentSenderForResult with the intentSender extracted from RecoverableSecurityException to grant the additional permission to delete file on Android Q.
Source: https://www.raywenderlich.com/9577211-scoped-storage-in-android-10-getting-started
i am new to android, i copied files to /storage/sdcard1 from host pc using adb push.
But unable to view the file from gallery application.It is showing through ls command and when i rebooted the device , gallery application showing files properly.But immediately it is not updating in gallery , so can any one help me out for this?
Thanks in advance
You'll have to notify the media scanner to capture metadata of the newly created files. Apps like Gallery work on the metadata database and not directly on the filesystem.
Programmatically you'd use MediaScannerConnection.
Since you're working with adb, you can send a broadcast to invoke media scanner.
Media scanner runs as part of the boot sequence so that's why it works after reboot.
Because your gallery DB isn't updated.
You can run media scanner manually
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
or Use
MediaStore.Images.Media.insertImage();
You can also insert gallery(media) DB by hand.
private Uri insertMediaStore(String dirPath, String filename, byte[] jpegByteArray) {
String filePath = dirPath + "/" + filename;
try {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, new Date().getTime());
values.put(Images.Media.ORIENTATION, "0");
String title = filename.replace(".jpg", "");
values.put(Images.Media.TITLE, title);
values.put(Images.Media.DISPLAY_NAME, filename);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.SIZE, jpegByteArray.length);
values.put("_data", filePath);
Uri uri = getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
OutputStream os = getContentResolver().openOutputStream(uri);
os.write(jpegByteArray);
os.close();
Logger.info("MediaStore Inserted URI:" + uri.toString());
return uri;
} catch(Exception ex) {
Logger.error(ex, "Failed to save the Bitmap file. FilePath: %s", filePath);
}
return null;
}
code reference: http://helloworld.naver.com/helloworld/1819
When I save an image to new location and then use MediaScanner to refresh the gallery then everything is fine - thumbnails and images are refreshed well.
But when I save an image to EXISTING location and then use MediaScanner - then only 'new' thumbnail isnt refreshed. (even though file is overwritten).
How to solve it?
Here is my code :
File file = new File(SDCARD_PATH, filename);
try {
FileOutputStream out = new FileOutputStream(file);
bmp.compress(format, BEST_IMAGE_QUALITY, out);
}catch (FileNotFoundException e) {
}
//refreshing single file using media scanner, no need to paste
This is a common and well know problem in Android. If you edit a media file, the thumbnail does not seem to update.
I have a fix for this, however, its still a fix and not a clean solution.
My fix is simple, and it basically deletes the stale thumbnail and then uses media scanner to update the thumbnails.
Here're the steps to be followed:
Step 1. Edit the file as you like. Say filename, "myVideoToBeEdited".
Step 2. Once you are done editing, delete its existing thumbnail.
First, get the video id using code like this:
final String[] columns = {
BaseColumns._ID, MediaColumns.DATA
};
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, columns, null, null, null);
boolean cancel = false;
if(null != cursor){
while(cursor.moveToNext() && !cancel){
String fileName = cursor.getString(cursor.getColumnIndex(MediaColumns.DATA));
int imageId = cursor.getInt(cursor.getColumnIndex(BaseColumns._ID));
if(fileName.equals(myVideoToBeEdited)){
removeVideoThumbnail(getContentResolver(), imageId); // step 3
cancel = true;
}
}
}
There are other ways to get the id, and more optimised ones as well.
Step 3. Delete the thumbnail.
public void removeVideoThumbnail(ContentResolver contentResolver, long photoId) {
Cursor thumbnails = contentResolver.query(android.provider.MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI, null, android.provider.MediaStore.Video.Thumbnails.VIDEO_ID + "=?", new String[]{String.valueOf(photoId)}, null);
for (thumbnails.moveToFirst(); !thumbnails.isAfterLast(); thumbnails.moveToNext()) {
long thumbnailId = thumbnails.getLong(thumbnails.getColumnIndex(android.provider.MediaStore.Video.Thumbnails._ID));
String path = thumbnails.getString(thumbnails.getColumnIndex(android.provider.MediaStore.Video.Thumbnails.DATA));
File file = new File(path);
if (file.delete()) {
contentResolver.delete(android.provider.MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI, android.provider.MediaStore.Video.Thumbnails._ID + "=?", new String[]{String.valueOf(thumbnailId)});
}
}
}
Or, here's the method to delete image thumbnail
public void removeImageThumbnail(ContentResolver contentResolver, long photoId) {
Cursor thumbnails = contentResolver.query(android.provider.MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, null, android.provider.MediaStore.Images.Thumbnails.IMAGE_ID + "=?", new String[]{String.valueOf(photoId)}, null);
for (thumbnails.moveToFirst(); !thumbnails.isAfterLast(); thumbnails.moveToNext()) {
long thumbnailId = thumbnails.getLong(thumbnails.getColumnIndex(android.provider.MediaStore.Images.Thumbnails._ID));
String path = thumbnails.getString(thumbnails.getColumnIndex(android.provider.MediaStore.Images.Thumbnails.DATA));
File file = new File(path);
if (file.delete()) {
contentResolver.delete(android.provider.MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, android.provider.MediaStore.Images.Thumbnails._ID + "=?", new String[]{String.valueOf(thumbnailId)});
}
}
}
Step 4. And finally use media scanner connection to scan the file so that it updates the thumbnails.
MediaScannerConnection.scanFile(context,
new String[] { myVideoToBeEdited }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
// pass the mime type, else passing a null will enable file extension to dictate the mime type
// you are good to go
}
});
Have you tried to remove the "old" picture prior to saving the new one to file system? Like so:
File file = new File(SDCARD_PATH, filename);
try {
// Delete the "old" file.
if (file.exists()) {
file.delete();
}
FileOutputStream out = new FileOutputStream(file);
bmp.compress(format, BEST_IMAGE_QUALITY, out);
}catch (FileNotFoundException e) {
}catch (SecurityException e) {
}
I save an image to the sdcard and it doesn't appear in the Gallery application until I pull off the sdcard and return it back.
Do you have any idea why is it so?
Seems like the Gallery application has some cache that isn't updated on file save...
Actually, I also want to open the just-saved image in Gallery application and have no success with that this is my question about this issue.
A simpler solution is to use the static convenience method scanFile():
File imageFile = ...
MediaScannerConnection.scanFile(this, new String[] { imageFile.getPath() }, new String[] { "image/jpeg" }, null);
where this is your activity (or whatever context), the mime-type is only necessary if you are using non-standard file extensions and the null is for the optional callback (which we don't need for such a simple case).
My answer to the original question and to anyone else that may have this problem:
I was having this same problem, images in my app that people saved to the SD card were not showing up in their Gallery immediately. After some searching I found this one line of code inserted after my 'save to sdcard' code that fixed the problem:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
The system scans the SD card when it is mounted to find any new image (and other) files. If you are programmatically adding a file, then you can use this class:
http://developer.android.com/reference/android/media/MediaScannerConnection.html
You can also add an Image to the Media Gallery by intent, have a look at the example code to see how it is done:
ContentValues image = new ContentValues();
image.put(Images.Media.TITLE, imageTitle);
image.put(Images.Media.DISPLAY_NAME, imageDisplayName);
image.put(Images.Media.DESCRIPTION, imageDescription);
image.put(Images.Media.DATE_ADDED, dateTaken);
image.put(Images.Media.DATE_TAKEN, dateTaken);
image.put(Images.Media.DATE_MODIFIED, dateTaken);
image.put(Images.Media.MIME_TYPE, "image/png");
image.put(Images.Media.ORIENTATION, 0);
File parent = imageFile.getParentFile();
String path = parent.toString().toLowerCase();
String name = parent.getName().toLowerCase();
image.put(Images.ImageColumns.BUCKET_ID, path.hashCode());
image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, name);
image.put(Images.Media.SIZE, imageFile.length());
image.put(Images.Media.DATA, imageFile.getAbsolutePath());
Uri result = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
Gallery refresh including Android KITKAT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
else
{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
Here is the code for the MediaScannerConnection:
MyMediaConnectorClient client = new MyMediaConnectorClient(newfile);
MediaScannerConnection scanner = new MediaScannerConnection(context, client);
client.setScanner(scanner);
scanner.connect();
newfile is the File object of your new/saved file.
there is an app in the emulator that says - ' Dev Tools'
click on that and select ' Media Scanning'.. all the images ll get scanned
Let your activity implement 'MediaScannerConnectionClient'
and add this to your activity:
private void startScan()
{
if(conn!=null) conn.disconnect();
conn = new MediaScannerConnection(YourActivity.this,YourActivity.this);
conn.connect();
}
#Override
public void onMediaScannerConnected() {
try{
conn.scanFile(yourImagePath, "image/*");
} catch (java.lang.IllegalStateException e){
}
}
#Override
public void onScanCompleted(String path, Uri uri) {
conn.disconnect();
}
this work with me
File file = ..... // Save file
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
File folderGIF = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/newgif2"); //path where gif will be stored
success = folderGIF.mkdir(); //make directory
String finalPath = folderGIF + "/test1.gif"; //path of file
.....
/* changes in gallery app if any changes in done*/
MediaScannerConnection.scanFile(this,
new String[]{finalPath}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Here I am sharing code that can load image in form of bitmap from and save that image on sdcard gallery in app name folder.
You should follow these steps
Download Image Bitmap first
private Bitmap loadBitmap(String url) {
try {
InputStream in = new java.net.URL(url).openStream();
return BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Please also provide following permission in your AndroidManifest.xml file.
uses-permission android:name="android.permission.INTERNET"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Here is whole code that is written in Activty in which we want to perform this task.
void saveMyImage(String appName, String imageUrl, String imageName) {
Bitmap bmImg = loadBitmap(imageUrl);
File filename;
try {
String path1 = android.os.Environment.getExternalStorageDirectory()
.toString();
File file = new File(path1 + "/" + appName);
if (!file.exists())
file.mkdirs();
filename = new File(file.getAbsolutePath() + "/" + imageName
+ ".jpg");
FileOutputStream out = new FileOutputStream(filename);
bmImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
ContentValues image = new ContentValues();
image.put(Images.Media.TITLE, appName);
image.put(Images.Media.DISPLAY_NAME, imageName);
image.put(Images.Media.DESCRIPTION, "App Image");
image.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
image.put(Images.Media.MIME_TYPE, "image/jpg");
image.put(Images.Media.ORIENTATION, 0);
File parent = filename.getParentFile();
image.put(Images.ImageColumns.BUCKET_ID, parent.toString()
.toLowerCase().hashCode());
image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, parent.getName()
.toLowerCase());
image.put(Images.Media.SIZE, filename.length());
image.put(Images.Media.DATA, filename.getAbsolutePath());
Uri result = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
Toast.makeText(getApplicationContext(),
"File is Saved in " + filename, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Hope that it can solve your whole problem.
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
Does not seem to work on KITKAT. It throws permission denial exception and crashes the app.
So for this, I have done the following,
String path = mediaStorageDir.getPath() + File.separator
+ "IMG_Some_name.jpg";
CameraActivity.this.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
.parse("file://" + path)));
Hope it helps.
Use this after saving the image
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
My code for MyMediaConnectorClient:
public class MyMediaConnectorClient implements MediaScannerConnectionClient {
String _fisier;
MediaScannerConnection MEDIA_SCANNER_CONNECTION;
public MyMediaConnectorClient(String nume) {
_fisier = nume;
}
public void setScanner(MediaScannerConnection msc){
MEDIA_SCANNER_CONNECTION = msc;
}
#Override
public void onMediaScannerConnected() {
MEDIA_SCANNER_CONNECTION.scanFile(_fisier, null);
}
#Override
public void onScanCompleted(String path, Uri uri) {
if(path.equals(_fisier))
MEDIA_SCANNER_CONNECTION.disconnect();
}
}
You need to give permissions to the Gallery app.
Just long press the gallery app icon in the home screen and tap on 'APP INFO' that pops up at the top of the screen. Doing it will show the gallery app settings. Now go in Permissions tab and enable the storage, camera permissions by toggling it.
Now go to your native gallery app and you will get the your saved images.
This will aslo solve your problem if your image in gallery are not showing instead they might showing a 404 type bitmap in midle.
please add a the tags that are in my code with your image because there must some meta data in order to show image in gallery.
String resultPath = getExternalFilesDir(Environment.DIRECTORY_PICTURES)+
getString(R.string.directory) + System.currentTimeMillis() + ".jpg";
new File(resultPath).getParentFile().mkdir();
try {
OutputStream fileOutputStream = new FileOutputStream(resultPath);
savedBitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e2) {
e2.printStackTrace();
}
savedBitmap.recycle();
File file = new File(resultPath);
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Photo");
values.put(MediaStore.Images.Media.DESCRIPTION, "Edited");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis ());
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(MediaStore.Images.ImageColumns.BUCKET_ID, file.toString().toLowerCase(Locale.US).hashCode());
values.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, file.getName().toLowerCase(Locale.US));
values.put("_data", resultPath);
ContentResolver cr = getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
return resultPath;
Try this one, it will broadcast about a new image created, so your image visible. inside a gallery.
photoFile replace with actual file path of the newly created image
private void galleryAddPicBroadCast() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(photoFile);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}