I wanna store an image in firebase storage but i got an warning message when running "Object does not exist at location", I don't know where is my mistake, already trying search old answer but all of them in java not kotlin.
class Activity2 : AppCompatActivity() {
private var curFile: Uri? = null
private val imageRef = Firebase.storage.reference
private val REQUEST_CODE_IMAGE_PICK = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity2)
//an image view to select and image inside phone storage
ivfoto.setOnClickListener {
Intent(Intent.ACTION_GET_CONTENT).also {
it.type = "image/*"
startActivityForResult(it, REQUEST_CODE_IMAGE_PICK)
}
}
//btn for upload image to storage
btnupload.setOnClickListener {
uploadImageToStorage("Myimages")
}
}
//function to upload an image to firebase
private fun uploadImageToStorage(filename: String) = CoroutineScope(Dispatchers.IO).launch {
try {
curFile?.let {
imageRef.child("images/$filename").putFile(it).await()
withContext(Dispatchers.Main) {
Toast.makeText(
this#Activity2, "Foto anda telah dipilih",Toast.LENGTH_LONG).show()
}
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
Toast.makeText(this#Activity2, e.message, Toast.LENGTH_LONG).show()
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_IMAGE_PICK) {
data?.data?.let {
curFile = it
ivfoto.setImageURI(it)
}
}
}
}
Here is the error message,its on the device,already run in physical device and emulator but the error is the same
Related
On my app, users can save some notes with image. But, users can not save their notes without image. Thus image is compulsory to save their data. But ı want to change it. I want to allow them to save their note without image. How can ı do this ? This is my saveclcikbutton codes;
class TakeNotesActivity : AppCompatActivity() {
var selectedPicture: Uri? = null
var selectedBitmap: Bitmap? = null
private lateinit var db: FirebaseFirestore
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_take_notes)
auth = FirebaseAuth.getInstance()
db = FirebaseFirestore.getInstance()
}
fun putPictureClick(view: View) {
val popupMenu = PopupMenu(this, view)
val inflater = popupMenu.menuInflater
inflater.inflate(R.menu.secondmenu, popupMenu.menu)
popupMenu.show()
popupMenu.setOnMenuItemClickListener {
if (it.itemId == R.id.galleryImage) {
if (ContextCompat.checkSelfPermission(
this,
android.Manifest.permission.READ_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this,
arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE),
1
)
} else {
val intentToGallery =
Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(intentToGallery, 2)
}
}
if (it.itemId == R.id.capturePhoto) {
if (ContextCompat.checkSelfPermission(
this,
android.Manifest.permission.CAMERA
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this,
arrayOf(android.Manifest.permission.CAMERA),
10
)
} else {
openCamera()
}
}
if (it.itemId == R.id.cancel) {
Toast.makeText(applicationContext, "Canceled", Toast.LENGTH_LONG).show()
}
true
}
}
fun openCamera() {
val values = ContentValues()
values.put(MediaStore.Images.Media.TITLE, "New Picture")
values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera")
selectedPicture =
contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
// Camera Intent
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, selectedPicture)
startActivityForResult(cameraIntent, 20)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
if (requestCode == 1) {
if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
val intentToGallery =
Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(intentToGallery, 2)
}
}
if (requestCode == 10) {
if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera()
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_LONG).show()
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == 2 && resultCode == Activity.RESULT_OK && data != null) {
selectedPicture = data.data
try {
if (selectedPicture != null) {
if (Build.VERSION.SDK_INT >= 28) {
val source =
ImageDecoder.createSource(this.contentResolver, selectedPicture!!)
selectedBitmap = ImageDecoder.decodeBitmap(source)
imageButton.setImageBitmap(selectedBitmap)
} else {
selectedBitmap =
MediaStore.Images.Media.getBitmap(this.contentResolver, selectedPicture)
imageButton.setImageBitmap(selectedBitmap)
}
}
} catch (e: Exception) {
}
}
//called when image was captured from camera intent
if (requestCode == 20 && resultCode == Activity.RESULT_OK && data != null) {
imageButton.setImageURI(selectedPicture)
}
super.onActivityResult(requestCode, resultCode, data)
}
fun saveClick(view: View) {
//UUID -> Image Name
val uuid = UUID.randomUUID()
val imageName = "$uuid.jpg"
val storage = FirebaseStorage.getInstance()
val reference = storage.reference
val imagesReference = reference.child("images").child(imageName)
if (selectedPicture != null) {
imagesReference.putFile(selectedPicture!!).addOnSuccessListener { taskSnapshot ->
// take the picture link to save the database
val uploadedPictureReference =
FirebaseStorage.getInstance().reference.child("images").child(imageName)
uploadedPictureReference.downloadUrl.addOnSuccessListener { uri ->
val downloadUrl = uri.toString()
println(downloadUrl)
val noteMap = hashMapOf<String, Any>()
noteMap.put("downloadUrl", downloadUrl)
noteMap.put("userEmail", auth.currentUser!!.email.toString())
noteMap.put("noteTitle", titleText.text.toString())
noteMap.put("yourNote", noteText.text.toString())
noteMap.put("date", Timestamp.now())
db.collection("Notes").add(noteMap).addOnCompleteListener { task ->
if (task.isComplete && task.isSuccessful) {
finish()
}
}.addOnFailureListener { exception ->
Toast.makeText(
applicationContext,
exception.localizedMessage?.toString(),
Toast.LENGTH_LONG
).show()
}
}
}
}
}
}
I also try to add on saveClick fun the codes below but did not work. What should I do ?
fun saveClick(view: View) {
//UUID -> Image Name
val uuid = UUID.randomUUID()
val imageName = "$uuid.jpg"
val storage = FirebaseStorage.getInstance()
val reference = storage.reference
val imagesReference = reference.child("images").child(imageName)
if (selectedPicture != null) {
imagesReference.putFile(selectedPicture!!).addOnSuccessListener { taskSnapshot ->
// take the picture link to save the database
val uploadedPictureReference =
FirebaseStorage.getInstance().reference.child("images").child(imageName)
uploadedPictureReference.downloadUrl.addOnSuccessListener { uri ->
val downloadUrl = uri.toString()
println(downloadUrl)
val noteMap = hashMapOf<String, Any>()
noteMap.put("downloadUrl", downloadUrl)
noteMap.put("userEmail", auth.currentUser!!.email.toString())
noteMap.put("noteTitle", titleText.text.toString())
noteMap.put("yourNote", noteText.text.toString())
noteMap.put("date", Timestamp.now())
db.collection("Notes").add(noteMap).addOnCompleteListener { task ->
if (task.isComplete && task.isSuccessful) {
finish()
}
}.addOnFailureListener { exception ->
Toast.makeText(
applicationContext,
exception.localizedMessage?.toString(),
Toast.LENGTH_LONG
).show()
}
}
}
}else {
val noteMap = hashMapOf<String, Any>()
noteMap.put("userEmail", auth.currentUser!!.email.toString())
noteMap.put("noteTitle", titleText.text.toString())
noteMap.put("yourNote", noteText.text.toString())
noteMap.put("date", Timestamp.now())
db.collection("Notes").add(noteMap).addOnCompleteListener { task ->
if (task.isComplete && task.isSuccessful) {
finish()
}
}
}
}
}
So all your logic is basically wrapped up in that putFile success callback, which requires an image to be successfully stored and retrieved (?) before anything will be added to the database.
You need to break that logic up, so you can only run the parts you want to - like just running the database update part if you don't have an image, or running that part later once your image is successfully handled.
So really, you need a "store in database" function to handle the final writing - call that directly if you don't have an image, call it in the success callbacks if you do. I'm just going to pseudocode this but:
saveData(noteMap: Map) {
add note to DB
}
saveClick() {
create noteMap with basic, non-image details (email, title etc)
if image is null, call saveData(noteMap)
else do the image stuff:
onSuccess:
add the downloadUrl to noteMap
call saveData(noteMap)
}
I see you've made an edit with an else branch which creates the map sans url and writes it - you're basically almost there, just make it a function instead, and pass the map in!
I've got a question about results/callback from activities to fragments.
Until now I have a fragment which calls a camera activity to scan QR Codes. So I start the activity from the fragment with startActivityForResult. If a QR Code is successfully scanned I get a callback Intent which is handled in onActivityResult.
This works perfectly.
Now I want to handle multiple scanns. In detail that means, that every successfully scan should call the onActivityResult function without closing the activity. The problem which I got at this point is, that onActivityResult is only called if I call finish() in the camera activity.
So my question is, how can I call onActivityResult multiple times with or without calling finish() but without closing the activity? Or is there another way to handle callbacks from activities to fragments?
This is my fragment code:
class ScanFragment : Fragment() {
private val CHECKIN_CODE = 0
private val CHECKOUT_CODE = 1
companion object {
fun newInstance(): LeadScanFragment = LeadScanFragment()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_lead_scan, container, false)
view.checkin.setOnClickListener {view ->
val intent = Intent(activity, CodeScannerActivity::class.java)
startActivityForResult(intent, CHECKIN_CODE)
}
view.checkout.setOnClickListener {view ->
val intent = Intent(activity, CodeScannerActivity::class.java)
startActivityForResult(intent, CHECKOUT_CODE)
}
return view
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == CHECKIN_CODE) {
if (resultCode == Activity.RESULT_OK) {
val returnString = data!!.getStringExtra("hash")
Log.d("scaned in", returnString)
}
}
if (requestCode == CHECKOUT_CODE) {
if (resultCode == Activity.RESULT_OK) {
val returnString = data!!.getStringExtra("hash")
Log.d("scaned out", returnString)
}
}
}
}
And this is the camera activity code:
class CodeScannerActivity : AppCompatActivity() {
private val requestCodeCameraPermission = 1001
private lateinit var cameraSource: CameraSource
private lateinit var detector: BarcodeDetector
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_code_scanner)
if (ContextCompat.checkSelfPermission(this#CodeScannerActivity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
askForCameraPermission()
} else {
setup()
}
}
private fun setup() {
detector = BarcodeDetector.Builder(this#CodeScannerActivity).build()
cameraSource = CameraSource.Builder(this#CodeScannerActivity, detector).setAutoFocusEnabled(true).build()
cameraSurfaceView.holder.addCallback(surfaceCallback)
detector.setProcessor(processor)
}
private fun askForCameraPermission() {
ActivityCompat.requestPermissions(this#CodeScannerActivity, arrayOf(Manifest.permission.CAMERA), requestCodeCameraPermission)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode == requestCodeCameraPermission && grantResults.isNotEmpty()) {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setup()
} else {
Toast.makeText(applicationContext, "Permission denied!", Toast.LENGTH_SHORT).show()
}
}
}
private val surfaceCallback = object : SurfaceHolder.Callback {
override fun surfaceCreated(surfaceHolder: SurfaceHolder?) {
try {
cameraSource.start(surfaceHolder)
} catch (exception: Exception) {
Toast.makeText(applicationContext, "Something went wrong", Toast.LENGTH_SHORT).show()
}
}
override fun surfaceChanged(p0: SurfaceHolder?, p1: Int, p2: Int, p3: Int) {
}
override fun surfaceDestroyed(p0: SurfaceHolder?) {
cameraSource.stop()
}
}
private val processor = object : Detector.Processor<Barcode> {
override fun release() {
}
override fun receiveDetections(detections: Detector.Detections<Barcode>?) {
val intent = Intent()
if(detections != null && detections.detectedItems.isNotEmpty()) {
val qrCodes: SparseArray<Barcode> = detections.detectedItems
val code = qrCodes.valueAt(0)
intent.putExtra("hash", code.displayValue)
setResult(Activity.RESULT_OK, intent)
finish()
} else {
setResult(Activity.RESULT_CANCELED, intent)
finish()
}
}
}
}
receiveDetections inside the processor in the lower area of the camera activity code is where the callback Intent is send back to onActivityResult.
You could have the scanner Activity send a local broadcast Intent to forward "results" to the calling Fragment. The Fragment (or its hosting Activity) should set a listener to listen for the broadcast "results". In this way you could perform multiple scans and send each result back to the underlying Activity.
Ive been trying to reverse engineer this project to understand more about zetbaitsu's Image Compression on github. Sad thing is, the code wont even compile. And I cant understand some of the code since its written in Java and not Kotlin.
Its been days since I started looking for a clear and straight to the point tutorial that tells how to compress image size. Can anyone tell me how I can compress Image file size and format.
If you have another way, please do include it bellow.
class MainActivity : AppCompatActivity() {
private lateinit var mainBinding: ActivityMainBinding
private lateinit var imageUri: Uri
// For Image Compression
private lateinit var actualImageFile: File
private lateinit var compressedImageFile: File
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
fetchDataInFirebaseDatabase()
buttonFunctions()
}
class CardView(val text: String, val imageUrl: String, val dataUuid: String) {
constructor(): this("", "", "")
}
class MainAdapter(val cardView: ArrayList<CardView>): RecyclerView.Adapter<CustomViewHolder>() {
class CustomViewHolder(val view: View): RecyclerView.ViewHolder(view)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.cardview_main, parent, false)
return CustomViewHolder(view)
}
override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
holder.view.apply {
cardView_textView.text = cardView[position].text
Picasso.get().load(cardView[position].imageUrl).into(holder.view.cardView_imageView)
}
}
override fun getItemCount(): Int {
return cardView.count()
}
}
private fun fetchDataInFirebaseDatabase() {
val databaseRef = FirebaseDatabase.getInstance().getReference("/")
val cardView = ArrayList<CardView>()
val mainAdapter = MainAdapter(cardView)
databaseRef.addChildEventListener(object : ChildEventListener{
override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?) {
snapshot.children.forEach {
val dataValue = it.getValue(CardView::class.java)
if (dataValue != null) cardView.add(dataValue)
mainAdapter.notifyDataSetChanged()
}
Log.d("MainFragment", "Number of children ${snapshot.key} = ${snapshot.childrenCount}")
}
override fun onChildChanged(snapshot: DataSnapshot, previousChildName: String?) {}
override fun onChildRemoved(snapshot: DataSnapshot) {
snapshot.children.forEach {
mainAdapter.notifyDataSetChanged()
}
}
override fun onChildMoved(snapshot: DataSnapshot, previousChildName: String?) {}
override fun onCancelled(error: DatabaseError) {}
})
mainBinding.activityMainGridRecyclerView.adapter = mainAdapter
}
private fun buttonFunctions() {
mainBinding.apply {
// Upload Text & Image in Firebase
activityMainUploadButton.setOnClickListener {
Log.d("MainActivity", "Uploading Data...")
//storeDataInFirebaseDatabase()
storeImageInFirebaseStorage()
}
// Choose an image in album
activityMainSelectPhotoButton.setOnClickListener {
Log.d("MainActivity", "Selecting Image...")
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, 0)
}
}
}
// Apply chosen image as button background
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 0 && resultCode == RESULT_OK && data != null) {
Log.d("MainActivity", "Image Selected")
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri)
mainBinding.activityMainSelectPhotoButton.apply {
text = ""
setBackgroundDrawable(BitmapDrawable(bitmap))
}
}
}
private var randomUUID: String? = null
private fun storeImageInFirebaseStorage() {
randomUUID = UUID.randomUUID().toString()
val storageRef = FirebaseStorage.getInstance().getReference("/FirebaseGridView/$randomUUID/")
storageRef.putFile(imageUri) // Store image URI in Firebase Storage
.addOnSuccessListener {
Log.d("MainActivity", "Image successfully stored in Firebase Storage")
Log.d("MainActivity", "Image size: ${it.metadata!!.sizeBytes}bytes / ${it.metadata!!.sizeBytes / 1000}kb")
storageRef.downloadUrl.addOnSuccessListener { // Get the image URL from Firebase Storage
storeDataInFirebaseDatabase(it.toString())
}
return#addOnSuccessListener
}.addOnFailureListener {
Log.d("MainActivity", "Image failed to store in Firebase Storage")
return#addOnFailureListener
}
}
// Stores data of CardView text/imageUrl/UUID in Firebase Database
private fun storeDataInFirebaseDatabase(imageUrl: String) {
val editText = mainBinding.activityMainInputEditText.text.toString()
val cardView = CardView(editText, imageUrl, randomUUID!!)
val databaseRef = FirebaseDatabase.getInstance().getReference("FirebaseGridView/$randomUUID/")
// Upload Data in FirebaseGridView/$randomUUID/ directory with the format/value of cardView
databaseRef.setValue(cardView)
.addOnSuccessListener {
Log.d("MainActivity", "Data successfully stored in Firebase Database")
Log.d("MainActivity", "\n \n Data Text: ${cardView.text} \n Data UUID: ${cardView. dataUuid} \n Image URL: ${cardView.imageUrl}")
Toast.makeText(this, "Data is stored", Toast.LENGTH_SHORT).show()
return#addOnSuccessListener
}.addOnFailureListener {
Log.d("MainActivity", "Data failed to be stored in Firebase Database")
Toast.makeText(this, "Data failed to store", Toast.LENGTH_SHORT).show()
return#addOnFailureListener
}
}
}
This is my failed attempt at trying to use Image Compress.
// TODO Compress Image file here
private fun customCompressImage() {
actualImageFile.let { imageFile ->
lifecycleScope.launch {
compressedImageFile = Compressor.compress(this#MainActivity, imageFile) {
//resolution(int)
quality(40)
format(Bitmap.CompressFormat.WEBP)
size(1_090_000) // 1mb
}
}
}
}
private fun setCompressedImage() {
compressedImageFile.let {
}
}
I use Intent.ACTION_PICK to take picture from gallery.
I already success when implement both activity, but found problem when using fragment.
I need some help, please.
Here MainActivity.kt
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
REQUEST_NEW_CHAT -> {
val name: String = data?.getStringExtra(PARAM_NAME) ?: ""
val phone: String = data?.getStringExtra(PARAM_PHONE) ?: ""
checkNewChatUser(name, phone)
}
//TODO: I.5. Update Status Page
REQUEST_CODE_PHOTO -> statusUpdateFragment?.storeImage(data?.data)
}
}
}
Here StatusUpdateFragment.kt
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
lay_progressbar.setOnTouchListener { v, event -> true }
btn_status.setOnClickListener { onUpdate() }
populateImage(context, imageUrl, img_status)
lay_status.setOnClickListener{
if(isAdded){
(activity as MainActivity).startNewActivity(REQUEST_CODE_PHOTO)
}
}
}
fun storeImage(imageUri: Uri?) {
if (imageUri != null && userId != null) {
//error message : Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
try {
Toast.makeText(activity, "Uploading...", Toast.LENGTH_SHORT).show()
lay_progressbar.visibility = View.VISIBLE
}
catch (e:Exception){
e.message
}
/*more code that i hide it...*/
}
}
Alhamdulillah, i already solved by Fahru.
MainActivity.kt : must add this at onActivityResult
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
REQUEST_NEW_CHAT -> {
val name: String = data?.getStringExtra(PARAM_NAME) ?: ""
val phone: String = data?.getStringExtra(PARAM_PHONE) ?: ""
checkNewChatUser(name, phone)
}
//TODO: I.5. Update Status Page
REQUEST_CODE_PHOTO -> statusUpdateFragment?.storeImage(data?.data,this)
}
}
}
StatusUpdateFragment.kt : must add context at storeImage
```
fun storeImage(imageUri: Uri?, context: Context) {
if (imageUri != null && userId != null) {
try {
Toast.makeText(context, "Uploading...", Toast.LENGTH_SHORT).show()
lay_progressbar.visibility = View.VISIBLE
}
catch (e:Exception){
e.message
}
//more code hidden
}
```
In this code, onActivityForResult is never called.
My Activity :
class PersonalInformationActivity : AppCompatActivity(), View.OnClickListener {
private val READ_REQUEST_CODE = 2
lateinit var user: User
lateinit var email: EditText
lateinit var phoneNumber: EditText
lateinit var username: EditText
lateinit var profilePicture: ImageView
lateinit var photoURI: Uri
//someCode
override fun onClick(v: View) {
when (v.id) {
R.id.profilePicture -> {
importPicture()
if (photoURI != null) {
try {
val file = FileUtil.from(this, photoURI)
RequestAddUserProfilePicture.MakeRequestTask(this, this).execute(user.token, file, photoURI.path!!.substring(photoURI.path!!.lastIndexOf("/") + 1))
Log.d("file", "File...:::: uti - " + file.path + " file -" + file + " : " + file.exists())
} catch (e: IOException) {
e.printStackTrace()
}
} else {
Toast.makeText(this, "need pic", Toast.LENGTH_LONG).show()
}
}
}
}
private fun importPicture() {
val intent = Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
setResult(Activity.RESULT_OK)
startActivityForResult(intent, READ_REQUEST_CODE)
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if (data != null) {
photoURI = data.data
Log.d("URI", "Uri:" + photoURI.toString())
}
}
}
}
I have read this answer: https://stackoverflow.com/a/19546302/7937498
and tried trick but didn't solve my problem.
Use different REQUEST_CODES for activity and fragment. I tried your code and tried different request codes 101 and 102, i got the result.
It's not a real way to solve but I refactor this from Kotlin to Java (exactly the same code) and it works as well...