简体   繁体   中英

How to delete a video from Gallery?

I've tried to delete my videos with this code, but on some devices they appear as damaged videos that can't be played in Gallery.

File videoFile = new File(filepath);
videoFile.delete();

How can I delete them properly?

Gallery is displaying mediastore data. To completely delete the file from the gallery you have to delete the mediastore database row for the video.

  • In code remove the record from the mediastore.

     // delete the mediastore entry; getContext().getContentResolver().delete(mediaStoreUri, null, null); 

Now all you need is the mediaStoreUri you can get it from the file path.

//found this on github 

https://gist.github.com/jdeloach/3172742

Problem with above link I would prefer they use the ContentUris.withAppendedId static method to get the Uri but instead they just add a slash and string it out

Uri mediaStoreUri = ContentUris.withAppendedId(
    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            ImageId);

Based on danny117's answer I found the solution for deleting videos in gallery:

/**
* Returns the Uri which can be used to delete/work with images in the photo gallery.
* @param filePath Path to IMAGE on SD card
* @return Uri in the format of... content://media/external/images/media/[NUMBER]
*/
private Uri getUriFromPath(String filePath) {
    long videoId;
    Uri videoUri = MediaStore.Video.Media.getContentUri("external");

    String[] projection = {MediaStore.Video.Media._ID};
    // TODO This will break if we have no matching item in the MediaStore.
   Cursor cursor = getContentResolver().query(videoUri, projection, MediaStore.Video.Media.DATA + " LIKE ?", new String[] { filePath }, null);
   cursor.moveToFirst();

   int columnIndex = cursor.getColumnIndex(projection[0]);
   videoId = cursor.getLong(columnIndex);

   cursor.close();
   return contentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoUri);
}

The Java code seems right, have you declared the WRITE_EXTERNAL_STORAGE in your manifest? If not, add <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> outside your <application> tag

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM