Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check whether file exists or not using content uri

I have a content uri of an audio file, which I got it from chooser intent.

content://com.mi.android.globalFileexplorer.myprovider/external_files/KannadaGeeta/11CHAPTER10.mp3

I just saved the above uri on database.

Now, when user opens my app again. I need to inform him whether the last mp3 file which he selected exists or not. If exists then only I must allow him to continue else I need to inform to download the file again.

but I stuck here completely, I'm not getting how to check a file exist or not with its content uri.

Kindly, help me to solve my issue.

like image 514
Vikas Acharya Avatar asked Nov 29 '25 17:11

Vikas Acharya


1 Answers

Method 1 :- Ok, Since Android team decided to deprecate getExternalStorageDirectory for security reason. Lot of things are not properly addressed by them.

for the question I don't find any proper answer. Anyhow here is a workaround by using deprecated method.

        var uri = Uri.parse("content://com.mi.android.globalFileexplorer.myprovider/external_files/KannadaGeeta/11CHAPTER10.mp3")
        var vidPath = uri.path
        vidPath = vidPath?.replace("external_files",Environment.getExternalStorageDirectory().toString())
        val file = File(vidPath)

        if (file.exists()) {
            println("log yes $file")
        } else {
            println("log no $file")
        }

This will work fine, but using this is left to you because of deprecated method.

Method 2 :- one more way is to use ACTION_OPEN_DOCUMENT then in onActivityResult it must add

val contentResolver = applicationContext.contentResolver
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or       
                     Intent.FLAG_GRANT_WRITE_URI_PERMISSION
contentResolver.takePersistableUriPermission(selectedVideoUri!!, takeFlags)

Then, finally with the content uri which is not expired, one can check for file existance.

DocumentFile.fromSingleUri(Uri.parse(contentUriStringfromdatabase)).exists()
like image 148
Vikas Acharya Avatar answered Dec 02 '25 05:12

Vikas Acharya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!