Android Scope Storage: Check Uri Exist

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        }    }}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.