android: usuwanie obrazu

Usuwam plik obrazu z mojej aplikacji. Robiłem

new  File(filename).delete ();

To było rzeczywiście usuwanie pliku. Ale obraz nadal był widoczny w galerii.

Podczas wyszukiwania stwierdziłem, że powinniśmy użyć

getContentResolver().delete(Uri.fromFile(file), null,null); usunąć

Ale tutaj dostaję wyjątek:

Nieznany adres URL pliku. java.lang.IllegalArgumentException: Unknown URL plik:///mnt/sdcard/DCIM/Camera / IMG_20120523_122612.jpg

Kiedy widzę z jakąkolwiek przeglądarka plików, ten konkretny obraz jest obecny. Pomóż mi rozwiązać ten problem. Czy istnieje inny sposób na aktualizację galerii, gdy obraz jest fizycznie usuwany

Author: Blackbelt, 2012-05-23

10 answers

Użyj poniższego kodu, może Ci to pomóc.

File fdelete = new File(file_dj_path);
if (fdelete.exists()) {
    if (fdelete.delete()) {
        System.out.println("file Deleted :" + file_dj_path);
    } else {
        System.out.println("file not Deleted :" + file_dj_path);
    }
}

aby odświeżyć galerię po usunięciu obrazu użyj poniższego kodu do wysłania transmisji

(dla

 sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
 Uri.parse("file://" +  Environment.getExternalStorageDirectory())));

Dla > = KITKAT API 14 użyj poniższego kodu

MediaScannerConnection.scanFile(this, new String[] { Environment.getExternalStorageDirectory().toString() }, null, new MediaScannerConnection.OnScanCompletedListener() {
            /*
             *   (non-Javadoc)
             * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
             */
            public void onScanCompleted(String path, Uri uri) 
              {
                  Log.i("ExternalStorage", "Scanned " + path + ":");
                  Log.i("ExternalStorage", "-> uri=" + uri);
              }
            });

Ponieważ:

ACTION_MEDIA_MOUNTED

Jest przestarzały w KITKAT(API 14).


Edytowano 04-09-2015

Sprawdzanie poprawności działania poniżej kodu

public void deleteImage() {
        String file_dj_path = Environment.getExternalStorageDirectory() + "/ECP_Screenshots/abc.jpg";
        File fdelete = new File(file_dj_path);
        if (fdelete.exists()) {
            if (fdelete.delete()) {
                Log.e("-->", "file Deleted :" + file_dj_path);
                callBroadCast();
            } else {
                Log.e("-->", "file not Deleted :" + file_dj_path);
            }
        }
    }

    public void callBroadCast() {
        if (Build.VERSION.SDK_INT >= 14) {
            Log.e("-->", " >= 14");
            MediaScannerConnection.scanFile(this, new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
                /*
                 *   (non-Javadoc)
                 * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
                 */
                public void onScanCompleted(String path, Uri uri) {
                    Log.e("ExternalStorage", "Scanned " + path + ":");
                    Log.e("ExternalStorage", "-> uri=" + uri);
                }
            });
        } else {
            Log.e("-->", " < 14");
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                    Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        }
    }

Poniżej logi

09-04 14:27:11.085    8290-8290/com.example.sampleforwear E/-->﹕ file Deleted :/storage/emulated/0/ECP_Screenshots/abc.jpg
09-04 14:27:11.085    8290-8290/com.example.sampleforwear E/-->﹕ >= 14
09-04 14:27:11.152    8290-8290/com.example.sampleforwear E/﹕ appName=com.example.sampleforwear, acAppName=/system/bin/surfaceflinger
09-04 14:27:11.152    8290-8290/com.example.sampleforwear E/﹕ 0
09-04 14:27:15.249    8290-8302/com.example.sampleforwear E/ExternalStorage﹕ Scanned /storage/emulated/0:
09-04 14:27:15.249    8290-8302/com.example.sampleforwear E/ExternalStorage﹕ -> uri=content://media/external/file/2416
 34
Author: Dhaval Parmar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-03 09:14:53

Widziałem wiele odpowiedzi sugerujących użycie

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" +  Environment.getExternalStorageDirectory())));

To działa, ale powoduje, że skaner mediów ponownie skanuje media w urządzeniu. Bardziej efektywnym podejściem byłoby zapytanie/usunięcie za pośrednictwem dostawcy treści sklepu multimedialnego:

// 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[] { file.getAbsolutePath() };

// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = 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();
 35
Author: Tanner Perrien,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-26 06:51:23
File file = new File(photoUri);
file.delete();

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(photoUri))));

Ten kod działa dla mnie i myślę, że lepiej niż przeinstalować całą kartę SD z Intent.ACTION_MEDIA_MOUNTED

 24
Author: Cody,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-23 09:36:16

Aby usunąć obrazek,

ContentResolver contentResolver = getContentResolver();
contentResolver.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            MediaStore.Images.ImageColumns.DATA + "=?" , new String[]{ imagePath });
 18
Author: Darshan Dorai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-22 17:45:25

Próbowałem tych wszystkich rozwiązań, ale nie miałem szczęścia w Androidzie 6.
W końcu znalazłem ten fragment kodu, który działał dobrze.

public static void deleteFileFromMediaStore(final ContentResolver contentResolver, final File file) {
    String canonicalPath;
    try {
        canonicalPath = file.getCanonicalPath();
    } catch (IOException e) {
        canonicalPath = file.getAbsolutePath();
    }
    final Uri uri = MediaStore.Files.getContentUri("external");
    final int result = contentResolver.delete(uri,
            MediaStore.Files.FileColumns.DATA + "=?", new String[]{canonicalPath});
    if (result == 0) {
        final String absolutePath = file.getAbsolutePath();
        if (!absolutePath.equals(canonicalPath)) {
            contentResolver.delete(uri,
                    MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
        }
    }
}
Testowałem to również w Androidzie 4.4 i 5.1 i działa idealnie.
 5
Author: Marco Menardi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-29 23:31:05
sendBroadcast(new Intent(
           Intent.ACTION_MEDIA_MOUNTED,
           Uri.parse("file://" +  Environment.getExternalStorageDirectory())));

Ten kod działa, ale jest bardzo kosztowny. Odmontowuje i montuje kartę SD, co może mieć wpływ na niektóre aplikacje lub zająć ogromne zasoby systemowe, aby odświeżyć galerię. Nadal szukam najlepszej alternatywy i opublikuję, jeśli ją dostanę.

 4
Author: Rajiv,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-22 14:05:15

W Kotlinie możesz to zrobić:

private fun deleteImage(path: String) {
    val fDelete = File(path)
    if (fDelete.exists()) {
        if (fDelete.delete()) {
            MediaScannerConnection.scanFile(this, arrayOf(Environment.getExternalStorageDirectory().toString()), null) { path, uri ->
                Log.d("debug", "DONE")
            }
        } 
    }
}
 1
Author: Jéwôm',
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-06 08:37:17

Miałem ten sam problem i próbowałem trzech różnych metod usuwania obrazu. Czasami działało, czasami nie. po zbyt długim czasie spędzonym teraz każda metoda, którą mam, usunie obraz.Chcę powiedzieć: Bądź ostrożny z przetwarzaniem bitmapy . Robiłem zdjęcie i w razie potrzeby obracałem:

public static Bitmap rotatePictureToPortraitMode(String filePath, Bitmap myBitmap) {
try {
    ExifInterface exif = new ExifInterface(filePath);
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
    Log.d("EXIF", "Exif: " + orientation);
    Matrix matrix = new Matrix();
    if (orientation == 6) {
        matrix.postRotate(90);
    } else if (orientation == 3) {
        matrix.postRotate(180);
    } else if (orientation == 8) {
        matrix.postRotate(270);
    }
    myBitmap = Bitmap.createBitmap(myBitmap, 0, 0, myBitmap.getWidth(), myBitmap.getHeight(), matrix, true); // rotating bitmap
} catch (Exception e) {

}
return myBitmap;
}

Po tym próbowałem usunąć obraz, ale jak powiedziałem wcześniej nie działa. Usunięcie tej metody pomogło mi rozwiązać problem.

Może to był tylko mój problem, ale jak tylko usunąłem to bardzo mi pomogło, więc chcę powiedzieć, że uważaj, jak przetwarzasz obraz. W moim przypadku użyłem wcześniej wymienionej odpowiedzi:

File file = new File(photoUri);
file.delete();

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, 
Uri.fromFile(new File(photoUri)))); 
Mam nadzieję, że to pomoże!
 1
Author: f.trajkovski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-06 17:28:09
public static boolean deltefolderwithimages(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i=0; i<children.length; i++) {
            boolean success = deltefolderwithimages(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }
    return dir.delete();
}
 0
Author: Gopal Reddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-08-28 07:22:08

DocumentFile.fromSingleUri(context, uri).delete();

Working great for me

 0
Author: Azhar Ali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-09-24 09:29:06