Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 221
prom85 Avatar asked Mar 06 '16 20:03

prom85


1 Answers

As fatboy pointed out, the behaviour is by design - documented in this google issue: https://issuetracker.google.com/issues/138887165

Solution:

There probably is no better solution than what I already posted in my question than following:

  • delete the file via DocumentFile object or with it's URI and DocumentsContract.deleteDocument
  • for an instant media store update (that's what I wanted) you must manually update the media store, e.g. by calling MediaScannerConnection.scanFile(...) like I already posted it in my question
like image 160
prom85 Avatar answered Oct 22 '22 09:10

prom85