Search code examples
javaandroidfiledirectorydelete-directory

can't delete file from external storage in android programmatically


I am trying to delete a file located at the path

/storage/714D-160A/Xender/image/Screenshot_commando.png

What I've done so far:

  try{
        String d_path = "/storage/714D-160A/Xender/image/Screenshot_commando.png";
        File file = new File(d_path);
        file.delete();

     }catch(Exception e){

        e.printStackTrace();
     }

and the file is still at its place(Not deleted :( )

Also I've given permission in Manifest file.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.STORAGE" />

Solution

  • public static boolean delete(final Context context, final File file) {
        final String where = MediaStore.MediaColumns.DATA + "=?";
        final String[] selectionArgs = new String[] {
                file.getAbsolutePath()
        };
        final ContentResolver contentResolver = context.getContentResolver();
        final Uri filesUri = MediaStore.Files.getContentUri("external");
    
        contentResolver.delete(filesUri, where, selectionArgs);
    
        if (file.exists()) {
    
            contentResolver.delete(filesUri, where, selectionArgs);
        }
        return !file.exists();
    }