【问题标题】:SAF - NullPointerException when copying file from private app folder to authorized SAF folderSAF - 将文件从私有应用程序文件夹复制到授权的 SAF 文件夹时出现 NullPointerException
【发布时间】:2020-01-28 13:15:11
【问题描述】:

我的应用必须将文件从私有应用文件夹复制到具有适当权限的 SAF 文件夹。

使用的代码是:

static boolean copyFileToTargetFolderWithNewName(Activity activity, String docUri,String targetFolderUri,String newName)
{
    deleteIfExisting(activity,Uri.parse(targetFolderUri),newName);

    File newFile = new File(docUri);
    Uri contentUri = FileProvider.getUriForFile(activity, "com.myappname.fileprovider", newFile);

    ContentResolver resolver = activity.getContentResolver();
    boolean result=false;

    Log.d("copy",contentUri+" "+targetFolderUri+" "+newName);

    try {
//error here
        Uri newUri=DocumentsContract.copyDocument(resolver,contentUri,Uri.parse(targetFolderUri)); 
        DocumentsContract.renameDocument(resolver,newUri,newName);
        result=true;
    } catch (FileNotFoundException e) {
        result=false;
    }
   return result;
}

日志输出产生:

D/copy: content://com.myappname.fileprovider/external_files/Android/data/com.myappname.app/files/subfolder/file.txt

content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2FSAFfolder/子文件夹

新名称.txt

怎么了? 这是标志问题吗?这两个域不兼容复制吗?

【问题讨论】:

    标签: android nullpointerexception file-copying android-fileprovider storage-access-framework


    【解决方案1】:

    您正在尝试复制非文档Uri (contentUri),并且the JavaDocs for copyDocument() 声明第一个参数必须是文档Uri

    带有 Document#FLAG_SUPPORTS_COPY 的文档,此值不得为空。

    DocumentsContractUri 称为“文档”时,表示通过DocumentsContract 本身获得的Uri。这将包括通过ACTION_OPEN_DOCUMENT 获得的Uri 或通过树DocumentFile 获得的Uri。但是,不包括

    • Uri.fromFile() 创建的Uri
    • 来自FileProvider.getUriForFile()Uri
    • Uri.parse()httphttps URL 创建的Uri

    【讨论】:

    • 我认为“这个值绝不能为空”的规定在所有三个参数的方法调用中都得到了满足。但在这种情况下,NullPointerError 仍然是一个奇怪的错误。
    • @P5music:没有堆栈跟踪,我无法对此发表评论。我的猜测是DocumentsContract 假设Uri 确实是一个文档Uri,尝试使用它创建一个query(),并在Cursor 中得到意想不到的结果。
    猜你喜欢
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    相关资源
    最近更新 更多