简体   繁体   中英

How To Delete A File Using MediaStore?

I just recently realized that Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) has been depreciated in Android Q . I've done some research that the following code works when downloading pictures from the internet.

String fileName = String.format(imageName, System.currentTimeMillis());
File dir = new File(Environment.DIRECTORY_PICTURES + "/MyFolder").getAbsoluteFile();
FileOutputStream outStream = null;
ContentResolver cr = getContentResolver();
ContentValues cv = new ContentValues();
cv.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
cv.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
cv.put(MediaStore.MediaColumns.RELATIVE_PATH, (Environment.DIRECTORY_PICTURES + "/MyFolder"));
Uri uri = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv);
assert uri != null;

scanFile(context, Uri.fromFile(dir));

try {
outStream = (FileOutputStream) cr.openOutputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext, "Picture Download Failed!", Toast.LENGTH_SHORT).show();
}

dir.mkdirs();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);

However, I can't seem to figure out how to delete this picture file that the code above created in "MyFolder"

I tried the following codes but to no avail...

cr.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null);

This works, but it deletes all picture files in "MyFolder" at once that was downloaded with the code above. I want it to delete the specified picture file corresponding with the fileName only. It should only delete one picture at-a-time.

File picFile = new File("/storage/emulated/0/Pictures/MyFolder/" + imageName + ".png");
Uri deleteUri = Uri.parse(picFile.toString());
cr.delete(deleteUri,null, null);

This doesn't work at all. It just crashes the app. Any solutions? Thanks!

Here is the crash code...

2020-03-25 05:10:10.763 17371-17371/com.exampleproject.myapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.exampleproject.myapp , PID: 17371
    java.lang.IllegalArgumentException: Unknown URL /storage/emulated/0/Pictures/MyFolder/The Late Late Show with James Corden.png
        at android.content.ContentResolver.delete(ContentResolver.java:1952)
        at com.exampleproject.myapp .MyAppPlayer$15.onClick(MyAppPlayer.java:1047)
        at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:191)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:7770)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1047)

I just tried the following code. It doesn't crash the app, but it doesn't delete anything.

Uri uri = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv);
assert uri != null;
cr.delete(uri, null, null);

I feel like I am getting closer, but it's still not working. Here is what I changed it to from your example code... It doesn't crash the app, but the file still doesn't delete.

String fileName = String.format(imageName, System.currentTimeMillis());
File dir = new File(Environment.DIRECTORY_PICTURES + "/MyFolder").getAbsoluteFile();
FileOutputStream outStream = null;
ContentResolver cr = getContentResolver();
ContentValues cv = new ContentValues();
String[] selArgs = new String[] {(myFile.getName())};
cv.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
cv.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
cv.put(MediaStore.MediaColumns.RELATIVE_PATH, (Environment.DIRECTORY_PICTURES + "/MyFolder"));

cr.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media._ID + "=?", selArgs);

If you want to delete specified picture :

Use

Uri uri = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv);

instead of

Uri deleteUri = Uri.parse(new File("/storage/emulated/0/Pictures/MyFolder/" + imageName + ".png"));

Because your file uri is something like this:

content://media/external/images/media/45

There is no delete uri, so you get this error "Unknown URL"

Delete func:

public Boolean deleteFile(Context context, Uri uri) {
    File file = new File(uri.getPath());
    String [] selectionArgs = {(file.getAbsolutePath())};
    ContentResolver contentResolver = context.getContentResolver();
    String where = null;
    Uri filesUri = null;
    if (android.os.Build.VERSION.SDK_INT >= 29) {
        filesUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        where = MediaStore.Images.Media._ID + "=?";
        selectionArgs = new String[] {(file.getName())};
    } else {
        where = MediaStore.MediaColumns.DATA + "=?";
        filesUri = MediaStore.Files.getContentUri("external");
    }

    int result =  contentResolver.delete(filesUri, where, selectionArgs);

    return file.exists();

}

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