🛠️ Fix error when getting file from full path
This commit is contained in:
parent
3fb8c18cec
commit
19c294779a
1 changed files with 24 additions and 28 deletions
|
|
@ -10,6 +10,7 @@ import android.content.Context
|
|||
import android.net.Uri
|
||||
import android.provider.DocumentsContract
|
||||
import com.anggrayudi.storage.file.DocumentFileCompat
|
||||
import com.anggrayudi.storage.file.getAbsolutePath
|
||||
|
||||
object CachedFileCompat {
|
||||
fun fromUri(context: Context, uri: Uri, builder: CachedFileBuilder? = null): CachedFile {
|
||||
|
|
@ -37,38 +38,33 @@ object CachedFileCompat {
|
|||
builder: CachedFileBuilder? = null
|
||||
): CachedFile? {
|
||||
val uri = try {
|
||||
val fullPathUri = DocumentFileCompat.fromFullPath(context, path)?.uri
|
||||
?: throw NullPointerException("Could not get URI from full path.")
|
||||
|
||||
fullPathUri
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
|
||||
try {
|
||||
val parentUri = DocumentFileCompat.getAccessibleRootDocumentFile(
|
||||
context = context,
|
||||
fullPath = path
|
||||
)?.uri
|
||||
?: throw NullPointerException("Could not get parent URI.")
|
||||
|
||||
val storageId = DocumentFileCompat.getStorageId(context, path)
|
||||
if (storageId.isBlank()) throw NullPointerException("Could not get storageId.")
|
||||
|
||||
val basePath = DocumentFileCompat.getBasePath(context, path)
|
||||
if (basePath.isBlank()) throw NullPointerException("Could not get basePath.")
|
||||
|
||||
val documentUri = DocumentsContract.buildDocumentUriUsingTree(
|
||||
parentUri,
|
||||
"$storageId:$basePath"
|
||||
)
|
||||
if (documentUri == null) throw NullPointerException("Could not get document URI.")
|
||||
val parentUri = context.contentResolver.persistedUriPermissions.find {
|
||||
try {
|
||||
val persistedUri = DocumentFileCompat.fromUri(context, it.uri)
|
||||
val persistedUriPath = persistedUri?.getAbsolutePath(context)
|
||||
|
||||
documentUri
|
||||
return@find !(persistedUri == null ||
|
||||
!persistedUri.canRead() ||
|
||||
persistedUriPath.isNullOrBlank() ||
|
||||
!path.startsWith(persistedUriPath, ignoreCase = true))
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
return@find false
|
||||
}
|
||||
}?.uri
|
||||
if (parentUri == null) throw NullPointerException("Could not get parentUri.")
|
||||
|
||||
DocumentsContract.buildDocumentUriUsingTree(parentUri, "$storageId:$basePath")
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
val cachedFile = CachedFile(
|
||||
context = context,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue