My Android has to copy a file from private app folder to a SAF location that was previously granted permissions and authorized. The code is:
static boolean copyDocumentFileToTargetFolderWithNewName(Activity activity, String docUri,String targetFolderUri,String newName)
{
deleteIfExisting(activity,Uri.parse(targetFolderUri),newName);
ContentResolver resolver = activity.getContentResolver();
boolean result=false;
Log.d("copy",docUri+" "+targetFolderUri+" "+newName);
Log.d("doc exists",String.valueOf(fileExists(activity,docUri))); //error here
try {
DocumentsContract.copyDocument(resolver,Uri.parse(docUri),Uri.parse(targetFolderUri));//or error here
DocumentsContract.renameDocument(resolver,Uri.parse(docUri),newName);
result=true;
} catch (FileNotFoundException e) {
result=false;
}
return result;
}
and
static public boolean fileExists(Activity activity,String fileUriString)
{
ContentResolver contentResolver;
contentResolver = activity.getContentResolver();
String parentFolderUriString=StringUtils.fromLastSlashLeft(fileUriString);
String fileName=StringUtils.fromLastSlashRight(fileUriString);
Uri parentFolderUri=Uri.parse(parentFolderUriString);
boolean exists;
DocumentFile docFile=DocumentFile.fromTreeUri(activity,parentFolderUri).findFile(fileName); //error here
exists= (null!=docFile);
return exists;
}
(with some self-explanatory string utility calls)
Here the result from the Log.d() line
D/copy: file:///storage/emulated/0/Android/data/com.myappname.app/folder/subfolder/file.txt content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2FSAFfolder/newname.txt
I get
java.lang.IllegalArgumentException: Invalid URI: file:///storage/emulated/0/Android/data/com.myappname.app/folder/subfolder/file.txt
at
DocumentFile docFile=DocumentFile.fromTreeUri(activity,parentFolderUri).findFile(fileName);
in the second method
or, when Log.d() is commented,
java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.ContentProviderClient.call(java.lang.String, java.lang.String, android.os.Bundle)' on a null object reference
at this line:
DocumentsContract.copyDocument(resolver,Uri.parse(docUri),Uri.parse(targetFolderUri));
in the first method. What's wrong with my code? Aren't private folder uris authorized? How to authorize them?