I've read all topics in this forum but nothing works for me. I have arraylist of paths of files and I need to delete some of them. In my code I try to use:
File file = new File(filesPath.get(0));
file.delete();
if (file.exists()) {
try {
file.getCanonicalFile().delete();
} catch (IOException e) {
e.printStackTrace();
}
if (file.exists()) {
file.getAbsoluteFile().delete();
}
}
Log.e("MyLogs", file.exists() ? "true" : "false");
filesPath I get from MediaStore and it looks like "/storage/extSdCard/mmm/bensound-summer.mp3". I can read this path without any problems, but I can't delete it. Here is my code for getting string array:
ArrayList<String> filesPath = new ArrayList<>();
Uri contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.Media.DATA};
try {
Cursor cursor = context.getContentResolver().query(
contentUri,
projection,
MediaStore.Audio.Media.IS_MUSIC + " != 0",
null,
null);
if (cursor != null && cursor.moveToFirst() && cursor.getCount() > 0) {
do {
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
File file = new File(path);
if (file.exists())
filesPath.add(path);
} while (cursor.moveToNext());
return filesPath;
} else {
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
Of course I added permissions to manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
From this link I took some code for mine but it didn't help me to solve my problem, that is why I wrote my question here.
EDIT:
Just found the point: I can't delete files from sdcard (removable)!!! from storage of decive everything deletes without any problem.
EDIT 2:
try {
long id = -1;
Cursor cursor = context.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media._ID },
MediaStore.Audio.Media.DATA + "=?",
new String[] { file.getAbsolutePath() },
null);
if (cursor != null && cursor.moveToFirst() && cursor.getCount() > 0) {
id = cursor.getLong(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
cursor.close();
Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
DocumentFile documentFile = DocumentFile.fromSingleUri(context, uri);
if (documentFile.delete()) {
Uri mediaContentUri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id
);
context.getContentResolver().delete(mediaContentUri, null, null);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
I got an exception error:
Failed to delete document
java.lang.UnsupportedOperationException: Unsupported call: android:deleteDocument
error points to line documentFile.delete()
it looks like "/storage/extSdCard/mmm/bensound-summer.mp3".
Then that file is on a removable micro SD card.
Micro SD cards are readonly for your app on modern Android systems.
That's why you cannot delete that file from it.
Well not in the way you try to do it now.
First Check Have You Got permission Read External Storage and Write External Storage then
You Can delete by this code..
You can just use File.delete()
File dir2 = new File(Environment.getExternalStorageDirectory() + "/Eraser/temp");
File dir = new File(Environment.getExternalStorageDirectory() + "/Eraser/Capture");
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
}
}
dir.delete();
if (dir2.isDirectory())
{
String[] children = dir2.list();
for (int i = 0; i < children.length; i++)
{
new File(dir2, children[i]).delete();
}
}
dir2.delete();
Are you sure that you have got the permission WRITE_EXTERNAL_STORAGE in your application before deleting the file?
As you can already access the file, there should not be any other problem calling the delete method. Moreover, you can also check log cat if there are any exceptions captured
i hope you add below permission in android manifest file..
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
for delete file used below code..
File file = new File(selectedFilePath);
boolean deleted = file.delete();
Related
when I get file path of file in Android 11 .
protected File getOutputMediaFile() {
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, timeStamp + ".jpg");
fileUri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Log.e("File Uri Path", "Uri inserted into media store = " + fileUri);
Toast.makeText(getActivity(), "File uri = "+fileUri, Toast.LENGTH_LONG).show();
String path = getImageRealPathFromURI(fileUri);
File file = new File(path);
return file;
}
private String getImageRealPathFromURI(Uri contentUri) {
String realPath = "";
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = getActivity().getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
realPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
} else {
Log.e("Image Real Path", "Cursor count appearing to be zero");
Toast.makeText(getActivity(), "Cursor count appearing to be zero", Toast.LENGTH_LONG).show();
realPath = "";
}
} catch (Exception e) {
Log.e("Image Real Path", "Exception fetching getImageRealPathFromURI() due to " + e.toString());
Toast.makeText(getActivity(),"Exception fetching getImageRealPathFromURI() due to "+e.toString(), Toast.LENGTH_LONG).show();
realPath = "";
} finally {
cursor.close();
}
return realPath;
}
I meet error : /storage/emulated/0/Pictures/1614237849822.jpg: open failed: EEXIST (File exists).
at libcore.io.IoBridge.open(IoBridge.java:492).
When I getOutputMediaFile().getpath.
Anyone help me?
add this line in manifest file :
android:requestLegacyExternalStorage="true"
and make sure that you add Read external storage permission and also allow this permission
The getContentResolver().insert() will give you a nice fresh uri to write the content of a file to.
It gives an uri you can use. It does not create a file for you.
Even if you get the path of the yet non existing file with the .DATA column, that file does not exist yet.
You can simply check that with File.exists().
Only if you open an OutputStream for the obtained uri and write to it the file will be created.
Use the uri! For what do you need that data path?
You can use this type to set mMediaRecoder's path:
final ParcelFileDescriptor parcelFileDescriptor = mContext.getContentResolver().
openFileDescriptor(Uri.parse(mVideoProfile.path), "rw");
mMediaRecorder.setOutputFile(parcelFileDescriptor.getFileDescriptor());
mVideoProfile.path = "content://media/external/video/media/751";
Im trying to delete a music file through my App but can't achieve that. Ive checked with
boolean exists = temp.exists();
boolean isFile = temp.isFile();
if there true and yes they are. These methods returns me true.
But when I come to the delete method :
boolean deleted = temp.delete();
It returns me False and the file is not getting deleted. There are no Exception throws just a false return to my deleted variable.
Im also using these permissons :
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.ACTION_HEADSET_PLUG"/>
Someone got an Idea for a solution ?
(Or other classes I can use ?)
Edit:
Thats my full code
File temp = new File(str_path);
boolean exists = temp.exists();
boolean isFile = temp.isFile();
if (exists)) {
boolean deleted = temp.delete();
if (deleted) {
Toast.makeText(context, "Successful deleted " + Title_Artist, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Not able to delete file " + Title_Artist, Toast.LENGTH_SHORT).show();
}
}
(And I checked while debuging if the object has his path in it and it have it)
Delete file music you must do two task:
Delete file in Storage.
public static boolean delete(File path) {
boolean result = true;
if (path.exists()) {
if (path.isDirectory()) {
for (File child : path.listFiles()) {
result &= delete(child);
}
result &= path.delete(); // Delete empty directory.
}
if (path.isFile()) {
result &= path.delete();
}
if (!result) {
Log.e("Delete", "Delete failed;");
}
return result;
} else {
Log.e("Delete", "File does not exist.");
return false;
}
}
Delete file from MediaStore:
public static void deleteFileFromMediaStore(final ContentResolver contentResolver, final File file) {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk >= android.os.Build.VERSION_CODES.HONEYCOMB) {
String canonicalPath;
try {
canonicalPath = file.getCanonicalPath();
} catch (IOException e) {
canonicalPath = file.getAbsolutePath();
}
final Uri uri = MediaStore.Files.getContentUri("external");
final int result = contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{canonicalPath});
if (result == 0) {
final String absolutePath = file.getAbsolutePath();
if (!absolutePath.equals(canonicalPath)) {
contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
}
}
}
}
You can reset/rescan MediaStore instead of do some code above.
Note: If you delete from SD card and android 4.4 +
Change for Android 4.4+ : Apps are not allowed to write (delete, modify
...) to external storage except to their package-specific directories.
The path from your comment looks like the file is on a removable SD card. You need special permissions on Android 4.4+ to manage or delete files on an SD card. You will need to use DocumentFile#delete().
For help accessing files on a removable SD card using DocumentFile see the following StackOverflow post:
How to use the new SD card access API presented for Android 5.0 (Lollipop)?
There is also a hack that might work without using DocumentFile as explained by the developer of FX file manager here: http://forum.xda-developers.com/showpost.php?p=52151865
Since you are checking that the file exists, there can only be one reason you can not delete the file: you don't have permissions to do it.
An app can not delete system files, or files of other apps.
Suppose your file path is
Environment.getExternalStorageDirectory().getPath()
+ "/Music"
+ "/"
+ "song.mp3"
delete it like this
File dir = new File(Environment.getExternalStorageDirectory()
.getPath()
+ "/Music");
if (dir.isDirectory()) {new File(dir, song.mp3).delete();}
if you want to delete all the files in music folder do this
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
new File(dir, children[i]).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();
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 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();