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) {
}
Related
I want to load the latest image from the external storage in Android.
Do you have any ideas how to get the name of the latest image?
Currently, I load a certain picture from the gallery this way:
File externalDirectory = Environment.getExternalStorageDirectory();
File directory = new File (externalDirectory.getAbsolutePath());
File file = new File(directory, "pic.jpg");
FileInputStream streamIn = null;
try {
streamIn = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
So is there a way to load the latest?
String[] projection = new String[]{
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, //the album it in
MediaStore.Images.ImageColumns.DATE_TAKEN,
MediaStore.Images.ImageColumns.MIME_TYPE
};
final Cursor cursor = getContext().getContentResolver()
.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
null, MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
// Put it in the image view
if (cursor.moveToFirst()) {
final ImageView imageView = (ImageView) findViewById(R.id.pictureView);
String imageLocation = cursor.getString(1);
File imageFile = new File(imageLocation);
if (imageFile.exists()) { // TODO: is there a better way to do this?
Bitmap bm = BitmapFactory.decodeFile(imageLocation);
imageView.setImageBitmap(bm);
}
}
Use content resolver
Updated :
if you mean you want to load an image from a certain directory you create for storing image you need to make sure in every device that certain directory is created. You can use a while loop to loop through all the image by checking wether the BUCKET_DISPLAY_NAME also known as album have the same name to your created album. If yes get the first picture since you already order it by descending order sort by date time.
int albumColumn = cur.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
do{
String album = cur.getString(albumColumn);
if(album == "YOUR CREATE DIR"){
break;
}
}while(cursor.moveToNext());
Integrate this code with the above code with your own logic. Basically the BUCKET_DISPLAY_NAME is the album which I mention earlier.
you may try this
String path = "/mnt/sdcard/Videos/Videoname"; // Your path
String fileName = new File(path).getName(); // you file name
Is there anyway to remove an exif thumbnail from an image?
I'm cropping images in my app and copying all exif data lossless with the sanselan library. Afterwards, I update width/height/rotation accordingly.
I could not find any way to update the exif thumbnail or to remove it, any ideas how to do that?
I have similar kind of problem of exif data
private void removeThumbnails(ContentResolver contentResolver, long photoId) {
try {
Cursor thumbnails = contentResolver.query(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Thumbnails.IMAGE_ID
+ "=?", new String[]{String.valueOf(photoId)}, null);
if (thumbnails != null) {
for (thumbnails.moveToFirst(); !thumbnails.isAfterLast() && !thumbnails.isBeforeFirst(); thumbnails.moveToNext()) {
long thumbnailId = thumbnails.getLong(thumbnails.getColumnIndex(MediaStore.Images.Thumbnails._ID));
String path = thumbnails.getString(thumbnails.getColumnIndex(MediaStore.Images.Thumbnails.DATA));
File file = new File(path);
if (file.delete()) {
contentResolver.delete(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, MediaStore.Images.Thumbnails._ID + "=?",
new String[]{String.valueOf(thumbnailId)});
}
}
thumbnails.close();
}
} catch (Exception e) {
}
}
So I have removed the thumbnail of it first then done the operation on the image
So u can try removing the thumbnail and try to crop it after
I am creating a file to send as an attachment to an email. Now I want to delete the image after sending the email. Is there a way to delete the file?
I have tried myFile.delete(); but it didn't delete the file.
I'm using this code for Android, so the programming language is Java using the usual Android ways to access the SD card. I am deleting the file in the onActivityResult method, when an Intent is returned to the screen after sending an email.
File file = new File(selectedFilePath);
boolean deleted = file.delete();
where selectedFilePath is the path of the file you want to delete - for example:
/sdcard/YourCustomDirectory/ExampleFile.mp3
Also you have to give permission if you are using >1.6 SDK
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
in AndroidManifest.xml file
Change for Android 4.4+
Apps are not allowed to write (delete, modify ...) to external storage except to their package-specific directories.
As Android documentation states:
"Apps must not be allowed to write to secondary external storage
devices, except in their package-specific directories as allowed by
synthesized permissions."
However nasty workaround exists (see code below). Tested on Samsung Galaxy S4, but this fix does't work on all devices. Also I wouldn’t count on this workaround being available in future versions of Android.
There is a great article explaining (4.4+) external storage permissions change.
You can read more about workaround here.
Workaround source code is from this site.
public class MediaFileFunctions
{
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static boolean deleteViaContentProvider(Context context, String fullname)
{
Uri uri=getFileUri(context,fullname);
if (uri==null)
{
return false;
}
try
{
ContentResolver resolver=context.getContentResolver();
// change type to image, otherwise nothing will be deleted
ContentValues contentValues = new ContentValues();
int media_type = 1;
contentValues.put("media_type", media_type);
resolver.update(uri, contentValues, null, null);
return resolver.delete(uri, null, null) > 0;
}
catch (Throwable e)
{
return false;
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private static Uri getFileUri(Context context, String fullname)
{
// Note: check outside this class whether the OS version is >= 11
Uri uri = null;
Cursor cursor = null;
ContentResolver contentResolver = null;
try
{
contentResolver=context.getContentResolver();
if (contentResolver == null)
return null;
uri=MediaStore.Files.getContentUri("external");
String[] projection = new String[2];
projection[0] = "_id";
projection[1] = "_data";
String selection = "_data = ? "; // this avoids SQL injection
String[] selectionParams = new String[1];
selectionParams[0] = fullname;
String sortOrder = "_id";
cursor=contentResolver.query(uri, projection, selection, selectionParams, sortOrder);
if (cursor!=null)
{
try
{
if (cursor.getCount() > 0) // file present!
{
cursor.moveToFirst();
int dataColumn=cursor.getColumnIndex("_data");
String s = cursor.getString(dataColumn);
if (!s.equals(fullname))
return null;
int idColumn = cursor.getColumnIndex("_id");
long id = cursor.getLong(idColumn);
uri= MediaStore.Files.getContentUri("external",id);
}
else // file isn't in the media database!
{
ContentValues contentValues=new ContentValues();
contentValues.put("_data",fullname);
uri = MediaStore.Files.getContentUri("external");
uri = contentResolver.insert(uri,contentValues);
}
}
catch (Throwable e)
{
uri = null;
}
finally
{
cursor.close();
}
}
}
catch (Throwable e)
{
uri=null;
}
return uri;
}
}
Android Context has the following method:
public abstract boolean deleteFile (String name)
I believe this will do what you want with the right App premissions as listed above.
Recursively delete all children of the file ...
public static void DeleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory()) {
for (File child : fileOrDirectory.listFiles()) {
DeleteRecursive(child);
}
}
fileOrDirectory.delete();
}
This works for me: (Delete image from Gallery)
File file = new File(photoPath);
file.delete();
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(photoPath))));
public static boolean deleteDirectory(File path) {
// TODO Auto-generated method stub
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
return(path.delete());
}
This Code will Help you.. And In Android Manifest You have to get Permission to make modification..
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Try this.
File file = new File(FilePath);
FileUtils.deleteDirectory(file);
from Apache Commons
Sorry: There is a mistake in my code before because of the site validation.
String myFile = "/Name Folder/File.jpg";
String myPath = Environment.getExternalStorageDirectory()+myFile;
File f = new File(myPath);
Boolean deleted = f.delete();
I think is clear...
First you must to know your file location.
Second,,, Environment.getExternalStorageDirectory() is a method who gets your app directory.
Lastly the class File who handle your file...
I had a similar issue with an application running on 4.4. What I did was sort of a hack.
I renamed the files and ignored them in my application.
ie.
File sdcard = Environment.getExternalStorageDirectory();
File from = new File(sdcard,"/ecatAgent/"+fileV);
File to = new File(sdcard,"/ecatAgent/"+"Delete");
from.renameTo(to);
This worked for me.
String myFile = "/Name Folder/File.jpg";
String my_Path = Environment.getExternalStorageDirectory()+myFile;
File f = new File(my_Path);
Boolean deleted = f.delete();
private boolean deleteFromExternalStorage(File file) {
String fileName = "/Music/";
String myPath= Environment.getExternalStorageDirectory().getAbsolutePath() + fileName;
file = new File(myPath);
System.out.println("fullPath - " + myPath);
if (file.exists() && file.canRead()) {
System.out.println(" Test - ");
file.delete();
return false; // File exists
}
System.out.println(" Test2 - ");
return true; // File not exists
}
You can delete a file as follow:
File file = new File("your sdcard path is here which you want to delete");
file.delete();
if (file.exists()){
file.getCanonicalFile().delete();
if (file.exists()){
deleteFile(file.getName());
}
}
File filedel = new File("/storage/sdcard0/Baahubali.mp3");
boolean deleted1 = filedel.delete();
Or, Try This:
String del="/storage/sdcard0/Baahubali.mp3";
File filedel2 = new File(del);
boolean deleted1 = filedel2.delete();
I am creating a file to send as an attachment to an email. Now I want to delete the image after sending the email. Is there a way to delete the file?
I have tried myFile.delete(); but it didn't delete the file.
I'm using this code for Android, so the programming language is Java using the usual Android ways to access the SD card. I am deleting the file in the onActivityResult method, when an Intent is returned to the screen after sending an email.
File file = new File(selectedFilePath);
boolean deleted = file.delete();
where selectedFilePath is the path of the file you want to delete - for example:
/sdcard/YourCustomDirectory/ExampleFile.mp3
Also you have to give permission if you are using >1.6 SDK
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
in AndroidManifest.xml file
Change for Android 4.4+
Apps are not allowed to write (delete, modify ...) to external storage except to their package-specific directories.
As Android documentation states:
"Apps must not be allowed to write to secondary external storage
devices, except in their package-specific directories as allowed by
synthesized permissions."
However nasty workaround exists (see code below). Tested on Samsung Galaxy S4, but this fix does't work on all devices. Also I wouldn’t count on this workaround being available in future versions of Android.
There is a great article explaining (4.4+) external storage permissions change.
You can read more about workaround here.
Workaround source code is from this site.
public class MediaFileFunctions
{
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static boolean deleteViaContentProvider(Context context, String fullname)
{
Uri uri=getFileUri(context,fullname);
if (uri==null)
{
return false;
}
try
{
ContentResolver resolver=context.getContentResolver();
// change type to image, otherwise nothing will be deleted
ContentValues contentValues = new ContentValues();
int media_type = 1;
contentValues.put("media_type", media_type);
resolver.update(uri, contentValues, null, null);
return resolver.delete(uri, null, null) > 0;
}
catch (Throwable e)
{
return false;
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private static Uri getFileUri(Context context, String fullname)
{
// Note: check outside this class whether the OS version is >= 11
Uri uri = null;
Cursor cursor = null;
ContentResolver contentResolver = null;
try
{
contentResolver=context.getContentResolver();
if (contentResolver == null)
return null;
uri=MediaStore.Files.getContentUri("external");
String[] projection = new String[2];
projection[0] = "_id";
projection[1] = "_data";
String selection = "_data = ? "; // this avoids SQL injection
String[] selectionParams = new String[1];
selectionParams[0] = fullname;
String sortOrder = "_id";
cursor=contentResolver.query(uri, projection, selection, selectionParams, sortOrder);
if (cursor!=null)
{
try
{
if (cursor.getCount() > 0) // file present!
{
cursor.moveToFirst();
int dataColumn=cursor.getColumnIndex("_data");
String s = cursor.getString(dataColumn);
if (!s.equals(fullname))
return null;
int idColumn = cursor.getColumnIndex("_id");
long id = cursor.getLong(idColumn);
uri= MediaStore.Files.getContentUri("external",id);
}
else // file isn't in the media database!
{
ContentValues contentValues=new ContentValues();
contentValues.put("_data",fullname);
uri = MediaStore.Files.getContentUri("external");
uri = contentResolver.insert(uri,contentValues);
}
}
catch (Throwable e)
{
uri = null;
}
finally
{
cursor.close();
}
}
}
catch (Throwable e)
{
uri=null;
}
return uri;
}
}
Android Context has the following method:
public abstract boolean deleteFile (String name)
I believe this will do what you want with the right App premissions as listed above.
Recursively delete all children of the file ...
public static void DeleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory()) {
for (File child : fileOrDirectory.listFiles()) {
DeleteRecursive(child);
}
}
fileOrDirectory.delete();
}
This works for me: (Delete image from Gallery)
File file = new File(photoPath);
file.delete();
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(photoPath))));
public static boolean deleteDirectory(File path) {
// TODO Auto-generated method stub
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
return(path.delete());
}
This Code will Help you.. And In Android Manifest You have to get Permission to make modification..
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Try this.
File file = new File(FilePath);
FileUtils.deleteDirectory(file);
from Apache Commons
Sorry: There is a mistake in my code before because of the site validation.
String myFile = "/Name Folder/File.jpg";
String myPath = Environment.getExternalStorageDirectory()+myFile;
File f = new File(myPath);
Boolean deleted = f.delete();
I think is clear...
First you must to know your file location.
Second,,, Environment.getExternalStorageDirectory() is a method who gets your app directory.
Lastly the class File who handle your file...
I had a similar issue with an application running on 4.4. What I did was sort of a hack.
I renamed the files and ignored them in my application.
ie.
File sdcard = Environment.getExternalStorageDirectory();
File from = new File(sdcard,"/ecatAgent/"+fileV);
File to = new File(sdcard,"/ecatAgent/"+"Delete");
from.renameTo(to);
This worked for me.
String myFile = "/Name Folder/File.jpg";
String my_Path = Environment.getExternalStorageDirectory()+myFile;
File f = new File(my_Path);
Boolean deleted = f.delete();
private boolean deleteFromExternalStorage(File file) {
String fileName = "/Music/";
String myPath= Environment.getExternalStorageDirectory().getAbsolutePath() + fileName;
file = new File(myPath);
System.out.println("fullPath - " + myPath);
if (file.exists() && file.canRead()) {
System.out.println(" Test - ");
file.delete();
return false; // File exists
}
System.out.println(" Test2 - ");
return true; // File not exists
}
You can delete a file as follow:
File file = new File("your sdcard path is here which you want to delete");
file.delete();
if (file.exists()){
file.getCanonicalFile().delete();
if (file.exists()){
deleteFile(file.getName());
}
}
File filedel = new File("/storage/sdcard0/Baahubali.mp3");
boolean deleted1 = filedel.delete();
Or, Try This:
String del="/storage/sdcard0/Baahubali.mp3";
File filedel2 = new File(del);
boolean deleted1 = filedel2.delete();
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