Tuesday, 6 August 2019

Correctly delete DocumentFile (respecting the MediaStore)

I have a DocumentFile defined in following two ways:

DocumentFile documentFile;
Uri documentFileUri;

I can delete a document file from the sd card via following methods:

  1. documentFile.delete();
  2. DocumentsContract.deleteDocument(contentResolver, documentFileUri);

But non of the above methods will delete the corresponding entry from the MediaStore.

What's the correct way to handle that? If I use the ContentProvider for deleting a local file, it will remove the File AND the row from the database (contentResolver.delete(localFileUri, null, null);). I would expect the same to happen if I use the DocumentsContract but it does not happen...

What I want

I want to instandly update the MediaStore. Normally I would call contentResolver.delete(documentFileUri, null, null); but this will fail with an exception that says, that the uri does not support deletions...

Question

Is there a more efficiant way to do it than my workaround?

Workaround

Currently I use following function to instantly update the media store after I deleted a DocumentFile:

public static boolean updateAfterChangeBlocking(String path, int timeToWaitToRecheckMediaScanner)
{
    final AtomicBoolean changed = new AtomicBoolean(false);
    MediaScannerConnection.scanFile(StorageManager.get().getContext(),
            new String[]{path}, null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    changed.set(true);
                }
            });

    while (!changed.get()) {
        try {
            Thread.sleep(timeToWaitToRecheckMediaScanner);
        } catch (InterruptedException e) {
            return false;
        }
    }

    return true;
}



from Correctly delete DocumentFile (respecting the MediaStore)

No comments:

Post a Comment