'registerForActivityResult doesn't work properly in android
I have fragment which uses camera activity. It waits data from this activity which is sent via intent. At the beginning I registered listener in the fragment:
private var resultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val data: Intent? = result.data
data?.let {
val file = File(data.extras?.getString("file_path")!!)
val uri = file.toUri()
}
}
}
and then after button click I launch my target activity:
val intent = Intent(context, CamActivity::class.java)
intent.putExtra("default_cam", true)
resultLauncher.launch(intent)
then in target activity after photo making I send data in such way:
val data = Intent()
data.putExtra("file_path", file.absolutePath)
setResult(RESULT_OK, data)
finish()
The problem is connected with processing activity results. When I open the app for the first time I can process data from the intent and enter to the data?.let{... block. But when I worked in some other app parts and then open this photo fragment I don't enter to data?.let{... block. I checked on the camera activity that photo data was sent, but my host fragment can't receive it without re-opening the app. I tried to unregister this receiver in such way:
override fun onDestroyView() {
super.onDestroyView()
resultLauncher.unregister()
}
but it didn't help me.
UPDATE
My scenario:
- open my app with fragments A,B(here we can open cam activity) and activity C (cam activity)
- open A -> move to B -> and press btn for camera activity (C) open
- make some photo
- return data from C to fragment B
- process it in activity result contract
- move to A (not camera fragment)
- return to B -> press btn and open camera activity (C)
- make photo and return data to camera fragment A
- activity contract can't process any received data
Solution 1:[1]
Try to use the provided intent and set Activity.RESULT_OK as result when sending data from CamActivity:
intent.putExtra("file_path", file.absolutePath)
setResult(Activity.RESULT_OK, intent)
finish()
Solution 2:[2]
Make sure you do the assignment inside onAttach or onCreate, i.e, before the activity is displayed. It should work.
fun openSomeActivityForResult() {
val intent = Intent(context, CamActivity::class.java)
intent.putExtra("default_cam", true)
resultLauncher.launch(intent)
}
var resultLauncher = registerForActivityResult(StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
// There are no request codes
val data: Intent? = result.data
doSomeThing()
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lpizzinidev |
| Solution 2 | Gaurav Rajput |
