Deleted image still shows in android gallery until

2019-02-19 02:05发布

I'm deleting a file as such

File fileToDelete =  new File("filepath");
Boolean fileDeleted =  fileToDelete.delete();

The fileDeleted is true and when I check the DDMS the file is not there but if I click on the gallery it still shows the image that was just deleted. I have to restart the emulator to see the change.

Is there any way to see the changes without having to restart the emaulator? I'm using eclipse

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-19 02:40

The gallery is using Android's media database to display the list of media. Deleting the file will not be reflected in the database until it scans the filesystem again. That is for example done after rebooting.

You can either delete the file directly through the database or force it to scan the file or folder you just deleted.

File fileToDelete =  new File("filepath");
boolean fileDeleted =  fileToDelete.delete();

// request scan    
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
scanIntent.setData(Uri.fromFile(fileToDelete));
sendBroadcast(scanIntent);
查看更多
霸刀☆藐视天下
3楼-- · 2019-02-19 02:42

You need to "clean" your project before build, and it will solve the issue. By default project is built using "cache" that does not always delete all previously constructed data.

查看更多
干净又极端
4楼-- · 2019-02-19 02:49

It is to do with how Gallery shows the Image files. Image file's Thumbnails are cached in the MediaStore and all the details are present in the Mediastore contentProvider.

Deleting the file will not update this database. But when you restart the emulator, Mediascanning is done by android. If MediaScanning can be triggered , gallery will stop showing the files

查看更多
做个烂人
5楼-- · 2019-02-19 03:01

I use the following code (which is also much like my code for creating a video which also tells the media system about file changes and correctly updates the Gallery):

private void deleteVideo(String videoUrl)
{
    File videoFile = new File(videoUrl);
    if (!videoFile.delete())
    {
        Log.e(TAG, "Failed to delete " + videoUrl);
    }
    else
    {
        MediaScannerConnection.scanFile(mContext,new String[] { videoUrl }, null, new MediaScannerConnection.OnScanCompletedListener() 
        {
            public void onScanCompleted(String path, Uri uri) 
            {
                Log.i("ExternalStorage", "Scanned " + path + ":");
                Log.i("ExternalStorage", "-> uri=" + uri);
            }
        });
    }
}
查看更多
登录 后发表回答