It would seem: what’s so complicated about Intent?

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

val badIntent = Intent(this, SomeActivity::class.java)
badIntent.putExtra("KEY_NAME", "Mike")
badIntent.putExtra("KEY_AGE", 29)
startActivity(badIntent)

In the other activity, we take:

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

And that’s it. But wait! How many pitfalls are there. Firstly, you can make a mistake in writing the key name, although this problem can be fixed with constants. But secondly, you can change the number or type of parameters passed in one of the activities and forget to change them to another (or the fifth, you never know how many of them cause this SomeActivity – you’ll forget one). Here it is worth using a technique in which the called 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, SomeActivity::class.java)
        with(Bundle()) {
            putString(NAME, name)
            putInt(AGE, age)
            intent.putExtras(this)
        }
        return intent
    }
}

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

Now this SomeActivity has a getCallingIntent method that takes context and all the parameters it needs. He returns full intent. By calling such a method from the first activity, it is impossible to miss a parameter or specify the wrong key, such an incorrect code simply will not compile. Here’s what the call looks like now:

startActivity(SomeActivity.getCallingIntent(
        context = this,
        name = "Mike",
        age = 29))

Easy peasy!

Leave a Reply