I can not read a file that I'm saving. I have declared and asking for storage permissions.
fun saveImage(bitmap: Bitmap, context: Context): String {
if (android.os.Build.VERSION.SDK_INT >= 29) {
val values = contentValues()
values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/" context.getString(R.string.app_name))
values.put(MediaStore.Images.Media.IS_PENDING, true)
// RELATIVE_PATH and IS_PENDING are introduced in API 29.
val uri: Uri? = context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values).also { uri ->
if (uri != null) {
if (uri != null) {
saveImageToStream(bitmap, context.contentResolver.openOutputStream(uri))
values.put(MediaStore.Images.Media.IS_PENDING, false)
context.contentResolver.update(uri, values, null, null)
}
//val split = file.path.split(":".toRegex()).toTypedArray() //split the path.
Log.d(
"Tag",
"v--- uri.path - ${uri.path}, "
)
return uri.path.toString() //assign it to a string(your choice).
}
}
} else { // below API 29 }
}
then in onCreate or any other method I want to access that file and show on preview.
val previousPath = """/external/images/media/356""" //preferenceManager.getString(...)
//val file = File(path)
//previewImage.setImageURI(Uri.parse(previousPath))
val file = FileUtils().getFile(applicationContext, Uri.parse(previousPath))
Log.d("Tag", "Yo --- " file?.path " , " file?.name)
// val myBitmap = BitmapFactory.decodeFile()
// previewImage.setImageBitmap()
But this is always empty. With this getFile method, I get null pointer exception. I need the file to upload to server. How can I get this file?
CodePudding user response:
val uri: Uri? = context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
You used that obtained uri to save your file content to storage with:
context.contentResolver.openOutputStream(uri)
Now if you wanna read that file use the same uri again. Just use:
context.contentResolver.openInputStream(uri)
Use the same uri!
Dont mess around with the File class.