Search code examples
storage-access-frameworkandroid-storagedocumentfile

Why does DocumentFile.getParentFile() return null after it is created with a Uri?


Code:

DocumentFile dfNew = dfDirectory.createFile("video/mp4", "foo.mp4");
//dfNew.getParentFile() is NOT null.  
DocumentFile dfNewCopy = DocumentFile.fromSingleUri(activity, dfNew.getUri());
//dfNewCopy.getParentFile() IS null. Otherwise, dfNewCopy works fine

Why is a DocumentFile created from a DocumentFile's Uri different from the original in this regard?


Solution

  • Storage Access Framework has been designed in days of API 16 for a very narrow use case (implementing the first official Android file picker). DocumentsProvider lacked a lot of useful functionality back then. Many more methods were added in following versions of platform.

    The method, required to check whether one Uri is parent of another Uri (isChildDocument) has been added in API 21.

    The method for getting parent of Uri (findDocumentPath) has been added in API 26 (Oreo).

    DocumentFile can not return the parent Uri on older platforms, because the system itself does not provide it there.