Невозможно удалить файл из хранилища - PullRequest
0 голосов
/ 11 октября 2019

Я пытаюсь удалить файл из памяти телефона, но он всегда возвращает false. Я уже попробовал большинство методов, приведенных в стеке, но ничего не работает.

 final File file = new File(path);
        if (path != null) {
            AlertDialog alertDialog = new AlertDialog
                    .Builder(getContext()).setTitle("Delete")
                    .setMessage("Are you sure you want to delete this video?")
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                               boolean fileDeleted =  file.delete();
                                Toast.makeText(getContext(), String.valueOf(fileDeleted), Toast.LENGTH_SHORT).show();
                            mAdapter.notifyDataSetChanged();
                        }
                    })
                    .setNegativeButton(android.R.string.cancel, null)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();
        }

Ответы [ 3 ]

0 голосов
/ 11 октября 2019

покажите мне путь к файлу, который вы передаете в файл, если вы запишете файл на SD-карту, вы не сможете его удалить, потому что в Android 4.4 приложения больше не могут записывать на карту micro SD.

0 голосов
/ 26 октября 2019

Это код, который я использовал после попытки многих методов.

private 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();
}
0 голосов
/ 11 октября 2019

Вы можете попробовать этот код:

public class FileUtils {

    public static boolean deleteFile(File file, Context context) {
        if (file == null || !file.exists()) return true;
        file.delete();
        if (file.exists()) {
            try {
                file.getCanonicalFile().delete();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (file.exists()) context.deleteFile(file.getName());
        }
        return !file.exists();
    }
}
...