简体   繁体   中英

Android - How to delete mp3 file from Internal Storage and SD Card - Java Code

I am trying to delete mp3 file.

My code:

 String path = songsList.get(position).getData();
 File fdelete = new File(path);
 if (fdelete.exists()) {
     if (fdelete.delete()) {
        DeleteRecursive(fdelete);
        Log.d(TAG, "deleted");
     } else {
        Log.d(TAG, "failed");
     }
 } else {
  Log.d(TAG, "file doesn't exist");
 }

When I delete initially, it gives "deleted" message. But, the file appears and not able to play. if again tries to delete it it shows "file doesn't exist" message.

Can anyone please tell me how to delete properly.

Any help would be appreciated. Thank you.

Finally, I managed to delete the mp3 file completely from internal storage as well as SD card.

Here is the code: (may help to someone)

 String[] projection = new String[]{BaseColumns._ID, MediaStore.MediaColumns.DATA};
 String selection = BaseColumns._ID + " IN (" + id + ")";

    try {
        final Cursor cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, selection,null, null);

       if (cursor != null) {

// remove from the media database

           context.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,selection, null);

// remove from storage / sdcard

            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                final String name = cursor.getString(1);
                try { 
                    final File f = new File(name);
                    if (!f.delete()) {
                        Log.e(TAG, "deleteSong: " + title + " can't be deleted");
                    }
                    cursor.moveToNext();
                } catch (@NonNull final SecurityException ex) {
                    cursor.moveToNext();
                } catch (NullPointerException e) {
                    Log.e(TAG, "Failed to find file " + name);
                }
            }
            cursor.close();
        }
        context.getContentResolver().notifyChange(Uri.parse("content://media"), null);

        Toast.makeText(context, title + " deleted", Toast.LENGTH_SHORT).show();

    } catch (SecurityException ignored) {
    }

Use this

public static void DeleteRecursive(File fileOrDirectory) {
          if (fileOrDirectory.isDirectory()) { 
                  for (File child :   fileOrDirectory.listFiles()) { 
                           DeleteRecursive(child);
                   } 
          } 
      fileOrDirectory.delete();
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM