У меня есть файл на карте памяти с путем: /storage/7AB3-1EEF/EXTERNAL_eicar-tf.com
С классом File
я могу прочитать его, но не могу удалить.
Итак, как мне удалить файл, используя только реальный путь к нему? Мой код работает, если файл хранится в /storage/0/[file]
Разрешения написаны в манифесте:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Код полностью работает на Android 4.2.2
Я попытался преобразовать файл в URI и удалить его, но у меня появляется сообщение об ошибке "Неизвестный URL".
Uri ur = Uri.fromFile(new File(reports.get(getAdapterPosition()).getPath()));
context.getContentResolver().delete(ur, null, null);
Код моей кнопки:
button_Delete_File.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
File file = new File(reports.get(getAdapterPosition()).getPath()); //Here comes out the described path...
file.delete();
Log.e("File deleted?", reports.get(getAdapterPosition()).getPath());
if (!file.exists()) {
Log.e("Yes", reports.get(getAdapterPosition()).getPath());
} else {
Log.e("No", reports.get(getAdapterPosition()).getPath());
Toast.makeText(context, context.getResources().getString(R.string.delete_file_error), Toast.LENGTH_SHORT).show();
}
}
});
Я это сделал! Спасибо за замечание г-на CommonsWare о Storage Access Framework, я смог переработать свой код:
button_Delete_File.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) { //Remove item from list and delete assigned file.
if (Build.VERSION.SDK_INT >= 19) {
try {
Uri uri = Uri.parse(reports.get(getAdapterPosition()).getPath());
ContentResolver contentResolver = context.getContentResolver();
contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
DocumentsContract.deleteDocument(contentResolver, uri);
reports.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
} catch (FileNotFoundException e) {
Toast.makeText(context, context.getResources().getString(R.string.delete_file_not_found), Toast.LENGTH_SHORT).show();
}
} else {
File file = new File(reports.get(getAdapterPosition()).getPath());
file.delete();
if (!file.exists()) {
reports.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
} else {
Toast.makeText(context, context.getResources().getString(R.string.delete_file_error), Toast.LENGTH_SHORT).show();
}
}
}
});
Теперь работает на Android 4.2.2 и 7.0.