Android Scope Storage: Check Uri Exist

May 6, 2022

Assuming you have the media/file uri based on MediaStore.MediaColumns._ID.

Solution 1

Use MediaFile.

val file = DocumentFile.fromSingleUri(context, uri)
if (file == null) {
    Timber.d("File not found: $uri")
}

Solution 2

Try to open file via ContentResolver.openInputStream

val isExist = try {
    context.contentResolver.openInputStream(uri)?.use {

    }
    true
}
catch (e: IOException) {
    false
}

Hybrid

fun checkUriExist(): Boolean {
    if (Build.VERSION.SDK_INT >= 29) {
        // Failed query: android.database.sqlite.SQLiteException: no such column: document_id (code 1 SQLITE_ERROR): , while compiling: SELECT document_id FROM video WHERE (_id=?) on SDK 28 on Emulator
        val docFile = DocumentFile.fromSingleUri(context, uri)
        return if (docFile?.exists() != true) {
            true
        } else {
            false
        }
    }
    else {
        try {
            context.contentResolver.openFileDescriptor(uri, "r").use { pfd ->
            // context.contentResolver.openInputStream(uri)?.use {
        

            }
            return true
        }
        catch (e: FileNotFoundException) {
            return false
        }
    }
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.