I have a file on a memory card with path: /storage/7AB3-1EEF/EXTERNAL_eicar-tf.com
With the File
class, I can read it, but I can't delete it.
So, how do I delete the file using only the real path to it? My code works if file stored in /storage/0/[file]
Permissions written in manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The code fully works on Android 4.2.2
I tried converting the file to a URI and deleting it, but I've got an "unknown URL" error message.
Uri ur = Uri.fromFile(new File(reports.get(getAdapterPosition()).getPath()));
context.getContentResolver().delete(ur, null, null);
My button's code:
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();
}
}
});
I did it! Thanks for Mr. CommonsWare's point about Storage Access Framework I was able to rework my code:
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();
}
}
}
});
Now it works on Android 4.2.2 and 7.0.
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.