How To Save And Check If The File Exists In Scoped Storage?
Till now, I check whether a file exists or not and if it does not then I save it to the device in Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) but
Solution 1:
Solution-1
privatefungetUriFromPath(displayName: String): Uri? {
val photoId: Longval photoUri = MediaStore.Images.Media.getContentUri("external")
val projection = arrayOf(MediaStore.Images.ImageColumns._ID)
val cursor = contentResolver.query(
photoUri,
projection,
MediaStore.Images.ImageColumns.DISPLAY_NAME + " LIKE ?",
arrayOf(displayName),
null
)!!
cursor.moveToFirst()
val columnIndex = cursor.getColumnIndex(projection[0])
photoId = cursor.getLong(columnIndex)
cursor.close()
return Uri.parse("$photoUri/$photoId")
}
if you want you can add relative path too to find at specific location
check using file name
privatefunisExist(){
val pathOfImage=getUriFromPath("myimage.png")
val isExist = try {
val i= pathOfImage?.let { contentResolver.openInputStream(it) }
i != null
}
catch (e: IOException) {
e.printStackTrace()
false
}
if (!isExist) {
// do whatever u want
}
}
this solution give exception when file not found and try to openstream.
Solution-2
In this solution I did save my files into
Android\media\com.yourpackge\
directory
privatefunisExist(){
val path = this.externalMediaDirs.first()
val folder = File(path, getString(R.string.app_name))
if (!folder.exists()) folder.mkdirs()
val file = File(folder, "myimage.png")
if (!file.exists()) {
// save your files or do whatever you want// use this for show files into gallery
MediaScannerConnection.scanFile(this, arrayOf(file.absolutePath), null,
object : MediaScannerConnection.OnScanCompletedListener {
overridefunonScanCompleted(path: String, uri: Uri?) {
Log.e("scann--","Finished scanning $path")
}
})
}
}
Now I want to move my files from older folder to getExternalStorageDirectory
Android\media\com.yourpackge\
directory in android 11 like whatsapp did without asking any permission.
EDIT - 1
I'm able to move my folder to new on using kotlin Utils
class
sourcefolder.copyRecursively(newfolder,true)
privatefuncopyFiles(){
val path = this.externalMediaDirs.first()
val folder = File(path, getString(R.string.app_name))
if (!folder.exists()) folder.mkdirs()
val sourcefolder = File(Environment.getExternalStorageDirectory().toString() + "/"
+"Supreme")
sourcefolder.copyRecursively(folder,true)
}
Post a Comment for "How To Save And Check If The File Exists In Scoped Storage?"