¿Cómo puedo eliminar archivos mediante programación en Android?
Estoy en 4.4.2, tratando de eliminar un archivo (imagen) a través de uri. Aquí está mi código:
File file = new File(uri.getPath()); boolean deleted = file.delete(); if(!deleted){ boolean deleted2 = file.getCanonicalFile().delete(); if(!deleted2){ boolean deleted3 = getApplicationContext().deleteFile(file.getName()); } }
En este momento, ninguna de estas funciones de eliminación está eliminando el archivo. También tengo esto en mi AndroidManifest.xml:
- Descubriendo todo acerca de la clase Uri de Android: uso y propósito
- Android Webview método shouldOverrideUrlLoading
- Imagen de Uri a bytesarray
- URI personalizado esquemas para el Facebook Messenger
- Cómo recuperar ImageUri de un ImageView?
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
- Image uri no muestra imágenes en ImageView en algún dispositivo Android
- "Android.intent.extra.STREAM"
- Pantalla de chat de Skype desde la intención
- ¿Cómo obtener el tono de llamada actual en Android?
- Buscar una categoría específica Play Store
- ¿Por qué ImageView.setImageURI () funcionaría en Android 2.2 pero no en 2.1?
- Cómo obtener HTML5 video URI en HTML5VFullScreen $ SurfaceVideoView en Android 4.0?
- Poner una imagen grande en un ImageView no funciona
¿Por qué no probar esto con este código:
File fdelete = new File(uri.getPath()); if (fdelete.exists()) { if (fdelete.delete()) { System.out.println("file Deleted :" + uri.getPath()); } else { System.out.println("file not Deleted :" + uri.getPath()); } }
Creo que parte del problema es que nunca intentes borrar el archivo, solo sigues creando una variable que tiene una llamada de método.
Así que en su caso usted podría intentar:
File file = new File(uri.getPath()); file.delete(); if(file.exists()){ file.getCanonicalFile().delete(); if(file.exists()){ getApplicationContext().deleteFile(file.getName()); } }
Sin embargo creo que eso es un poco excesivo.
Añadiste un comentario de que estás utilizando un directorio externo en lugar de un uri. Así que en su lugar debe agregar algo como:
String root = Environment.getExternalStorageDirectory().toString(); File file = new File(root + "/images/media/2918");
A continuación, intente eliminar el archivo.
Prueba éste. Está funcionando para mí.
handler.postDelayed(new Runnable() { @Override public void run() { // Set up the projection (we only need the ID) String[] projection = { MediaStore.Images.Media._ID }; // Match on the file path String selection = MediaStore.Images.Media.DATA + " = ?"; String[] selectionArgs = new String[] { imageFile.getAbsolutePath() }; // Query for the ID of the media matching the file path Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; ContentResolver contentResolver = getActivity().getContentResolver(); Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null); if (c.moveToFirst()) { // We found the ID. Deleting the item via the content provider will also remove the file long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID)); Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id); contentResolver.delete(deleteUri, null, null); } else { // File not found in media store DB } c.close(); } }, 5000);
He probado este código en el emulador de Nougat y funcionó:
En manifiesto añadir:
<application... <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths"/> </provider> </application>
Cree una carpeta xml vacía en la carpeta res y pasada en el directorio provider_paths.xml:
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-path name="external_files" path="."/> </paths>
A continuación, coloque el siguiente fragmento en su código (por ejemplo fragmento):
File photoLcl = new File(homeDirectory + "/" + fileNameLcl); Uri imageUriLcl = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationContext().getPackageName() + ".provider", photoLcl); ContentResolver contentResolver = getActivity().getContentResolver(); contentResolver.delete(imageUriLcl, null, null);
Veo que has encontrado tu respuesta, pero no funcionó para mí. El borrado seguía volviendo falso, así que probé lo siguiente y funcionó (Para cualquier otra persona para quien la respuesta elegida no funcionó):
System.out.println(new File(path).getAbsoluteFile().delete());
El sistema de salida puede ser ignorado, obviamente, lo puse por conveniencia de confirmar la eliminación.