In Kotlin, to upload an image to Firestore I want to give the users 2 options, choose image from gallery or take a picture. Choosing image from gallery works with no issue, but, if I take a picture, I'm not able to upload to Firestore.
The app fails because "imageUrl = data?.data" is null.
Here is a copy of my code, any help is greatly appreciated:
Main Activity
private fun camera() {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent, CAMERA_REQUEST_CODE)
}
private fun gallery() {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(intent, GALLERY_REQUEST_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == CAMERA_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
var pic : Bitmap? = data?.getParcelableExtra<Bitmap>("data")
profileImage.setImageBitmap(pic)
imageUrl = data?.data //This is null
println("From Camera...${data?.data}")
}
}
if (requestCode == GALLERY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
imageUrl = data?.data //valid
profileImage.setImageURI(imageUrl)
println("From Gallery...${data?.data}")
}
}
}
fun uploadUserImage() {
if (imageUrl != null && userId != null) {
val fileName = UUID.randomUUID()
val filePath = FirebaseStorage.getInstance().reference
.child("profileImages").child(userId!!).child(fileName.toString())
var bitmap: Bitmap? = null
try {
bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUrl)
} catch (e: IOException) {
e.printStackTrace()
}
val baos = ByteArrayOutputStream()
bitmap?.compress(Bitmap.CompressFormat.JPEG, 40, baos)
val data = baos.toByteArray()
val uploadTask = filePath.putBytes(data)
uploadTask.addOnFailureListener { e -> e.printStackTrace() }
uploadTask.addOnSuccessListener { taskSnapshot ->
filePath.downloadUrl.addOnSuccessListener { uri ->
updateImageUrl(uri.toString())
}
}
}
}