My Android app has to check whether a folder Uri is already present on the filesystem (the parent folder was selected by the user, so it is authorized). The following code is intendend to perform the check:
static public boolean folderExists(Activity activity,String folderUriString)
{
ContentResolver contentResolver;
contentResolver = activity.getContentResolver();
Log.d("folder name",folderUriString); // it's content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Faccesspoint1/subfoldername
Uri folderUri = Uri.parse(folderUriString);
boolean isTreeUri=DocumentsContract.isTreeUri(folderUri);
boolean exists = DocumentFile.fromTreeUri (activity,folderUri).exists();
Log.d("is treeUri",String.valueOf(isTreeUri)); //true
Log.d("folder exists",String.valueOf(exists)); //true
return exists;
}
This code doesn't work because it yields true value if the folder doesn't exist (never created, or created and deleted) even if the parent folder itself doesn't exist.
Note that the uri doesn't exist yet for sure. I use the filesystem app on my device to inspect directories.
The uri string is created by means of this method:
public static String appendUriString(String originalUriString,String appendedUriPath)
{
String result;
Uri uri=Uri.parse(originalUriString);
result=Uri.withAppendedPath(uri,appendedUriPath).toString();
Log.d("appendUri",result);
return result;
}
content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Faccesspoint1/subfoldername
As you can see the resulting uri is a mixed form with encoded and non-encoded symbols, so it is legit because a SAF method created the complete uri.
A different version of the folderExists method split the uri strings to have the parent folder. But I think that a uri should be verified without this trick. Why does it not work? What is the right code?