Search code examples
androiddocument

DocumentsContract.copyDocument() always fails


final String AUTHORITY = "com.android.externalstorage.documents";

Uri roottree  = DocumentsContract.buildTreeDocumentUri(AUTHORITY,"primary:");
Uri sourceuri = DocumentsContract.buildDocumentUriUsingTree(roottree,DocumentsContract.geTreeDocumentId(roottree) + "Folder1");
Uri TargetUri = DocumentsContract.buildDocumentUriUsingTree(roottree,DocumentsContract.getTreeDocumentId(roottree) + "Folder2");
Uri resulturi = DocumentsContract.copyDocument(myContentResolver,sourceuri,TargetUri);

Copying Folder1 into Folder2 always return null. CreateDocument, DeleteDocument even MoveDocument working without any issue.


Solution

  • I believe it was a deliberately bug. It didn't work and you need to rebuild the function. Here is simple sample:

    public boolean copyFileUri(Uri FilePath, Uri ToFolder, String Name){boolean done=true;
        try {
            InputStream in = this.getContentResolver().openInputStream(FilePath);
            Uri uriOut=DocumentsContract.createDocument(getContentResolver(), ToFolder,  "text/plain", Name );
            OutputStream out = new FileOutputStream(getContentResolver().openFileDescriptor(uriOut, "w").getFileDescriptor());
            Uri uRename=DocumentsContract.renameDocument(getApplicationContext().getContentResolver(), uriOut, Name );
            if (uRename==null){/*RENAME WITH WHILE COUNTER*/}
            try { byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch(Exception e){done=false;}
            out.close(); in.close();
        } catch(Exception e){done=false;} return done;      
    }
    

    Note that you will need to DIY additional function for these case:

    • The destination folder have files with the same name, you need to add counter for rename or a switch to overwrite old file.
    • If you want to copy folder, it will a little more complex by add:
      • Detect Uri was folder or normal file
      • Create folder
      • Scan File
      • Recursion calling itself when scan so it scan whole the tree.