in my kotlin app, i want to add a listener to a button which allows the user to open the…
- User
in my kotlin app, i want to add a listener to a button which allows the user to open the image library on the device and pick a photo. the photo’s location in the internal storage is then returned, and the app can save it in some location. i dont want to use deprecated functions
- Assistant
To achieve this, you can use the following code:
val pickImage = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? -> if (uri != null) { // Do something with the selected image URI val imageLocation = saveImageToInternalStorage(uri) } } val pickImageButton: Button = findViewById(R.id.pick_image_button) pickImageButton.setOnClickListener { pickImage.launch("image/*") } private fun saveImageToInternalStorage(uri: Uri): String { val inputStream = contentResolver.openInputStream(uri) val type = contentResolver.getType(uri) ?: "image/png" val extension = when (type) { "image/jpeg" -> "jpg" "image/png" -> "png" else -> "jpg" } val file = File(filesDir, "${UUID.randomUUID()}.$extension") val outputStream = FileOutputStream(file) inputStream?.copyTo(outputStream) return file.absolutePath } - User
if i want to save the file’s path, wouldnt it be better if in my app, i saved the result of the saveimagetointernalstorage rather than the images uri?
- Assistant
Yes, saving the path of the saved file in your app's data (such as in a database or shared preferences) would be a better approach as it would allow you to retrieve the image in the future even if the original URI may have changed or been deleted.
To do this, you can modify the code as follows:
val pickImage = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? -> if (uri != null) { // Do something with the selected image URI val imageLocation = saveImageToInternalStorage(uri) saveImagePath(imageLocation) // Save the file path in your app's data storage } } val pickImageButton: Button = findViewById(R.id.pick_image_button) pickImageButton.setOnClickListener { pickImage.launch("image/*") } private fun saveImageToInternalStorage(uri: Uri): String { val inputStream = contentResolver.openInputStream(uri) val type = contentResolver.getType(uri) ?: "image/png" val extension = when (type) { "image/jpeg" -> "jpg" "image/png" -> "png" else -> "jpg" } val file = File(filesDir, "${UUID.randomUUID()}.$extension") val outputStream = FileOutputStream(file) inputStream?.copyTo(outputStream) return file.absolutePath } private fun saveImagePath(path: String) { // Save the file path in your app's data storage (such as in a database or shared preferences) } - User
now, i want to be able to display images in a recyclerview. so, i already have a prepared list of image locations. i want to get the image at the specified location, and insert it into my recyclerview
- Assistant