Simple way to manage activity for result

Vadim Hudym
Sep 7, 2018 · 1 min read

Very simple way to manage startActivityForResult and onActivityResult with Kotlin to avoid the boilerplate code.

Previously, it was very annoying for me to manage whole start activity for result flow. I should did something like this:
1) Create variable for request code.
2) Call startActivityForResult().
3) Handle activity result in onActivityResult().

The main problem was different locations of start activity code and code of handling result. And it was uncomfortable to search one part from another part this one-piece process via REQUEST_CODE.

To solve this problem we can add following code to base activity or fragment:

private val handlerArray: SparseArray
<(resultCode: Int, data: Intent?) -> Unit> = SparseArray()

protected fun Intent.startForResult(
f: (resultCode: Int, data: Intent?) -> Unit) {
val requestCode = handlerArray.size() + 1
startActivityForResult(this, requestCode)
handlerArray.append(requestCode, f)
}
override fun onActivityResult(requestCode: Int,
resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
handleOnActivityResult(requestCode, resultCode, data)
}

private fun handleOnActivityResult(requestCode: Int,
resultCode: Int, data: Intent?) {
handlerArray[requestCode]?.let { it(resultCode, data) }
}

Everything is clear here. We use SparseArray to keep handling functions.We add extension-function for Intent, where requestCode is generated, method startActivtityForResult is called and handling function is added to array. Then we get handling function from array and invoke it. If you really worry about request code you can add it to extension-function parameters. And next time to start activity for result you can do this:

val intent = Intent(context, AnotherActivity::class.java) intent.startForResult { resultCode, data -> 
//do something
}

I hope this will be useful for somebody.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade