case R.id.menu_delete:
File photoToDelete = new File(photoPath, photoList[gPosition]);
photoToDelete.delete();
checkPhotoFolder();
galleryAdapter.notifyDataSetChanged();
Log.d("position", "" + gPosition);
return true;
I'm manually delete a photo file using above code. But in the system gallery the photo still show the blank thumbnail.
The question is how can I delete the photo file and also the thumbnail of it in the gallery?
Try invoke the MediaScanner to refresh the gallery
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Code from Google's example
Try this.
getContentResolver().delete(Uri.fromFile(photoToDelete), null, null);
You must update the data structure (eg. list or array) that stores the photos.
I guess it is photoList.
So you should do (assuming photoList is an array):
photoList = photoList.asList().remove(gPosition).toArray();
Related
I am saving a video to public folder using
private File createVideoFile(){
if(!isExternalStorageWritable()){
return null;
}
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "vid121.mp4");
return file;
}
However I tried also PICTURES, and VIDEOS
and no matter what folder I try, the video does not appear when the user opens default gallery app (or even any app that shows videos). I navigated to the folder through Files app and I can see the video.
How can I make sure the video appears as part of gallery?
Thank you
You need to rescan gallery. Because Gallery refreshed by default at boot time.
Try this.
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
I have a method to start the camera and take a photo (working with API 24 and Higher) :
public void invokeCamera()
{
// create the image Uri
Uri pictureUri = FileProvider.getUriForFile(getContext(),getContext().getPackageName() + ".provider",createImageFile());
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// tell the camera where to save
intent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);
// permission for saving the image
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent,CAPTURE_REQ_CODE);
}
creating the image File:
private File createImageFile() {
File picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String imgName = "myImageName_0X0Y02_test.jpg";
return new File(picturesDirectory.getPath(),"picture" + imgName );
}
the problem is :
this code is working without errors but sometimes i can't see the image in the Gallery , sometimes when i open the gallery after about 10 mins i see it there ! this is weird and i'm confused , am i missing something ?
All permissions are granted (Camera and full access to Storage)
Since you work with API 24 and higher, I will provide the code for it only. Basically, you need to tell the media scanner that a file was added so it can scan and add it straight away:
public static void scanMediaForChanges(Context context, File file){
MediaScannerConnection.scanFile(context,
new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
You are number #### with this problem. You should tell the media store about your new file.
To do that invoke the media scanner for your file.
Code has been posted a ### times. So google.
I am downloading some of the images from server to sd card in a folder. Images are storing in sd card successfully. But the problem is that at the same time images are not showing in gallery. If i restart the device then it will be showing in gallery.
How can I refresh the gallery programmatically so images can be visible simultaneously whenever I fetch images from server?
I got it, below code will scan your image file and make it available simultaneously to gallery also:
MediaScannerConnection.scanFile(context,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
I want to add taken photos to MediaStore so Gallery app can find them (without restarting device).
App's min sdk is 9. Any help, blog or documentation appreciated.
On most devices, all you need to do is wait a little while and the new photos will be detected automatically.
If you want to preform an immediate refresh to the gallery, you need to use the MediaScanner class, It will refresh the gallery - remove deleted photos, add new ones and so on...
public void refreshGallery() {
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
String newPhotoPath = "file:" + image.getAbsolutePath(); // image is the created file image
File file = new File(newPhotoPath);
Uri contentUri = Uri.fromFile(file);
scanIntent.setData(contentUri);
sendBroadcast(scanIntent);
}
Hope this helped!
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
Insert this line of code after your 'save' code.
This will trigger a media scan and all media files in all folders (except with '.nomedia' files) will be updates & visible in gallery.
Source.
MediaScanner Documentation.
OR
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Google's Sample Code.
ok its my code and it work for me it give all images which i can see in Android Gallery just call this function from this line
getallimages(Environment.getExternalStorageDirectory());
and my function is below
private void getallimages(File dir)
{
String[] STAR = { "*" };
final String orderBy = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
Cursor imagecursor = cntx.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STAR, null, null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
int count = imagecursor.getCount();
for (int i = 0; i < count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
ImageItem imageItem = new ImageItem();
if(new File(imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA))).length()<=10485760)
{
imageItem.filePath = imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA));
imageItem.id = id;
imageItem.selection = false; //newly added item will be selected by default
controller.images.add(imageItem);
}
}
}
You can ask the MediaScanner to scan a specific file, ie your image file on demand. This should produce less overhead than just asking the MediaScanner to scan everything for new files.
SO: how to run media scanner in android
I've added an inserted in Gallery using android API as following:
Images.Media.insertImage(ctx.getContentResolver(),
"scard/test.jpg", "Hello" ,
"description");
Actually the image that I passed its full path (scard/test.jpg) is already successfully inserted in the DB, but when you open the gallery you can't see it unless you switch off/on the device or Mount/Unmount the external memory.
It there any way to refresh the gallery on demand?
Thanks
Bassel Kh.
I encountered this problem recently, I tried #Samuh's solution, but not works perfectly until I found the solution from Google's example:
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
I tried myself and worked flawlessly.
Or, similarly, you might want to take a look at the reference of the MediaScanner Class and someone on StackOverflow asked this question before:
Image, saved to sdcard, doesn't appear in Android's Gallery app
The solution using the Media Scanner (sendBroadcast). But, probably, on sdcards with a lot of pics and data, this operation should reach a high processing cost.
There is another solution, after saving your media file on gallery, you should notify the gallery DB that another file was inserted. That can be done like that:
private void addImageGallery( File file ) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); // or image/png
getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
This code doesn't save your media file to gallery, only saves the information about a new file in the gallery DB. You should store real file before.
This solution is faster because the gallery will not be fully re-scanned. But is not so trustful because all the information about the file was added manually.
static public boolean resetExternalStorageMedia(Context context) {
if (Environment.isExternalStorageEmulated())
return (false);
Uri uri = Uri.parse("file://" + Environment.getExternalStorageDirectory());
Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED, uri);
context.sendBroadcast(intent);
return (true);
}
static public void notifyMediaScannerService(Context context, String path) {
MediaScannerConnection.scanFile(context,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
You can use this for refresh Android Gallery:
public void refreshAndroidGallery(Uri fileUri) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(fileUri);
mContext.sendBroadcast(mediaScanIntent);
} else {
mContext.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
}
i tied everything then I found this perfect solution!
You can apply this method for any file type (jpg, png,pdf, etc)
public void refreshGallery(File f) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri fileUri = Uri.fromFile(f); //out is your output file
mediaScanIntent.setData(fileUri);
sendBroadcast(mediaScanIntent);
} else {
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
}
then
refreshGallery(newFileName);
newFIleName is a file path you can get your file path as
File newFileName = new File(filePath + "/" + fileName + ".jpg");