Android Katha: onActivityResult is Deprecated. Now What?
Hi and welcome to my blog,
During our Android application development, we have been using startActivityForResult and onActivityResult methods a lot for the sake of callbacks from activities. It was really-clear and easy to implement. But Google knows.
Unfortunately, now we are getting a warning for this method in our code.
So the question is, Now What?
And the answer is: ActivityResultLauncher.
Pros:
- We can now launch activities for the result from fragments and receive the results in fragments without going through the activity.
- Instead of distinguishing requests with fallible INT codes we now have strongly typed classes.
- We can have separate callbacks for separate requests, eliminating the need for switch-case in response handling.
onActivityResult(Kotlin):
fun openSecondActivityForResult() { val intent = Intent(this, SecondActivity::class.java) startActivityForResult(intent, REQUEST_CODE) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE) { // Do operations } }
ActivityResultLauncher(Kotlin):
fun openSecondActivityForResult() { val intent = Intent(this, SecondActivity::class.java) activityResultLauncher.launch(intent) } // We can do the assignment inside onAttach or onCreate var activityResultLauncher = registerForActivityResult(StartActivityForResult()) { result -> // There are no request codes if (result.resultCode == resultCode1 && result.data != null) { // Do operations } else if (result.resultCode == resultCode2) { // Do operations } }
— — — — — — — — How to replace existing calls— — — — — — — —
Steps to replace old one with the new one (Kotlin):
- In place of overridden method onActivityResult(…), use
// We can do the assignment inside onAttach or onCreate var activityResultLauncher = registerForActivityResult(StartActivityForResult()) { result -> // There are no request codes if (result.resultCode == resultCode1 && result.data != null) { // Do operations } else if (result.resultCode == resultCode2) { // Do operations } }
2. In place of startActivityForResult(intent, REQUEST_CODE), use
val intent: Intent = Intent(this, SecondActivity::class.java)
activityResultLaunch.launch(intent)
3. In SecondActivity.java class, while returning back to the source activity, code will remain the same like –
val intent = Intent()
setResult(FirstActivity.resultCode1, intent)
finish()
Please find the complete code with some demo screens on GitHub
Thanks for visiting, Keep reading & keep improving 🙂