It would seem: what is so dificult in the Intent ?

But there are nuances. Intent is declared, startActivity() is called with it and that’s it. Well, or with the addition of extra. Easy. Or not?

val badIntent = Intent(this,
badIntent.putExtra("KEY_NAME", "Mike")
badIntent.putExtra("KEY_AGE", 29)

Get in second activity:

val name = intent.getStringExtra("KEY_NAME")
val age = intent.getIntExtra("KEY_AGE", 0)

That’s all. BUT! Many problems on this way. First, you can make a typo in the key name, although this problem can be eliminated with the help of constants. But secondly, you can change number or type of parameters in one of the activity and forget to change them in another (or fifth, you never know how many SomeActivity causes them there – you will definitely forget one). Here it is worth using a hint in which the invoked activity itself knows how to call it and what parameters it needs.:

companion object {

    private const val NAME = "KEY_NAME"
    private const val AGE = "KEY_AGE"

    fun getCallingIntent(context: Context, name: String, age: Int): Intent {
        val intent = Intent(context,
        with(Bundle()) {
            putString(NAME, name)
            putInt(AGE, age)
        return intent

val name = intent.extras.getString(NAME)
val age = intent.extras.getInt(AGE)

Now this SomeActivity has getCallingIntent method, wich takes context and all needed parameters an returns intent. Calling this method from the first activity, you never forget something or make a mistake with parameters types, this wrong code just won’t compile. This is what the call now looks like:

        context = this,
        name = "Mike",
        age = 29))

Easy peasy!

Leave a Reply

Close Menu