0

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()

dmytro
  • 246
  • 8
  • 21

4 Answers4

1

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();
1

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.

greenapps
  • 11,154
  • 2
  • 16
  • 19
  • please, explain me how to delete files from sdcard. I'll be very appreciate to you for this. and YOU ARE RIGHT! I've checked: if I selete files from xternal storage (not sdcard) it deletes well, but if I try to do thesame from sdcard - it doesn't work – dmytro May 03 '18 at 15:02
  • Thank sir! I think I will find solution for my problem in several moments – dmytro May 03 '18 at 15:46
  • I almost decided my problem, but to delete DocumentFile I got exception Unsupported call: android:deleteDocument. I think I need to add android.permission.MEDIA_CONTENT_CONTROL, but system says that permission is only granted to system app. So, how to solve this problem? Any suggestions, please – dmytro May 03 '18 at 18:21
  • ??? I cannot help you if i dont see your code. Post your code in an extra code block please. – greenapps May 03 '18 at 18:37
  • That is pretty strange code. Never seen such. And what is the value of file.getAbsolutePath() that you use? And why do you use two different delete() calls? – greenapps May 03 '18 at 18:56
  • According to some sites I understood that documentFile deletes the file itself, and contentResolver deletes attributes of file but it doesn't delete file itselt. that is why I delete it twice – dmytro May 03 '18 at 18:59
  • Your code is rubbisch. To delete a file from sdcard you can first let the user select that file with ACTION_OPEN_DOCUMENT. Or let the user choose a directory with ACTION_OPEN_DOCUMENT_TREE. After that you can do with the contents of that directory what you want. – greenapps May 03 '18 at 19:00
  • Ok, in my app I have a list with files, user can select some of them and do several actions, like read and delete. For now, reading works. So, user select files to delete from list, I create array and in other thread delete them all. in this case I want to avoid to use ACTION_OPEN_DOCUMENT, because I don't want to ask user to select something second time. – dmytro May 03 '18 at 19:05
  • I understand. But sorry that will not go. You have file scheme paths and you cannot convert them to content scheme paths and even if you could you would not have the needed permissions which you would obtain by the actions i mentioned. – greenapps May 03 '18 at 19:08
  • `in my app I have a list with files` Redesign your app so it works with a list of content schemes for files. Adapt to modern times. – greenapps May 03 '18 at 19:10
  • "Adapt to modern times" - I thought using design all in one app without adding other system activities was the modern style! :) But, you are right, I can't get correct uri for my files and I can't use permission MEDIA_CONTENT_CONTROL. – dmytro May 03 '18 at 19:14
  • @dmytro did you found a solution for deleting the files on sd card? I have the same problem and it only deletes the file when it is on the internal storage. – Vince VD Feb 08 '19 at 13:15
  • No, it's restriction of OS – dmytro Apr 11 '19 at 23:43
  • Humm i have same issue. If it's not possible, how do explorer apps like Es Explorer do delete SD Card files ? – Zack Dec 22 '20 at 13:58
0

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

Fahed Yasin
  • 400
  • 2
  • 9
  • Of cause I wrote permissions to manifest. I got no exceptions, just file.delete() returns false – dmytro May 03 '18 at 14:58
0

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();