Android Scope Storage: Check Uri Exist
May 6, 2022Assuming 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
}
}
}
- algo-trading
- algolia
- analytics
- android
- android-ktx
- android-permission
- android-studio
- apps-script
- bash
- binance
- bootstrap
- bootstrapvue
- chartjs
- chrome
- cloud-functions
- coding-interview
- contentresolver
- coroutines
- crashlytics
- crypto
- css
- dagger2
- datastore
- datetime
- docker
- eslint
- firebase
- firebase-auth
- firebase-hosting
- firestore
- firestore-security-rules
- flask
- fontawesome
- fresco
- git
- github
- glide
- godot
- google-app-engine
- google-cloud-storage
- google-colab
- google-drive
- google-maps
- google-places
- google-play
- google-sheets
- gradle
- html
- hugo
- inkscape
- java
- java-time
- javascript
- jetpack-compose
- jetson-nano
- kotlin
- kotlin-serialization
- layout
- lets-encrypt
- lifecycle
- linux
- logging
- lubuntu
- markdown
- mate
- material-design
- matplotlib
- md5
- mongodb
- moshi
- mplfinance
- mysql
- navigation
- nginx
- nodejs
- npm
- nuxtjs
- nvm
- pandas
- payment
- pip
- pwa
- pyenv
- python
- recylerview
- regex
- room
- rxjava
- scoped-storage
- selenium
- social-media
- ssh
- ssl
- static-site-generator
- static-website-hosting
- sublime-text
- ubuntu
- unit-test
- uwsgi
- viewmodel
- viewpager2
- virtualbox
- vue-chartjs
- vue-cli
- vue-router
- vuejs
- vuelidate
- vuepress
- web-development
- web-hosting
- webpack
- windows
- workmanager
- wsl
- yarn