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