Android Activity Return Result (Kotlin)

Apr 13, 2019

Activty return result.

class ResultActivity : AppCompatActivity() {    companion object {        const val RESULT_ID = "id"        const val RESULT_NAME = "name"        fun newInstance(context: Context) = Intent(context, ResultActivity::class.java)    }    // call this to return result and close activity    fun returnResult(id: Int, name: String) {        val data = Intent().apply {            putExtra(RESULT_ID, id)            putExtra(RESULT_NAME, name)        }        setResult(RESULT_OK, data)        finish()    }}

Call ResultActivity to return result

class MainActivity : AppCompatActivity() {    companion object {        private const val REQUEST_RESULT = 1    }    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {        super.onActivityResult(requestCode, resultCode, data)        if (requestCode == REQUEST_RESULT) {            if (resultCode == Activity.RESULT_OK && data != null) {                // success                data.apply {                    val id = getIntExtra(ResultActivity.RESULT_ID, 0)                    val name = getStringExtra(ResultActivity.RESULT_NAME)                    // do something                }            }            else {                // fail            }        }    }    fun requestResult() {        startActivityForResult(ResultActivity.newInstance(), REQUEST_RESULT)    }}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.