Intent Builder for activities
Android architecture patterns for dummies
I have learned a lot about Java, Kotlin and Android before getting my first job as Android developer. On interviews, and later on my first days in big company I have found a lot of knowledge gaps about common best practices used for simple frequent tasks.
In this series of articles I want to share these tiny architecture patterns often used in big projects. This is my generalized experience, structured and simplified for better understanding. It’s not about global architecture, but about small thing making your everyday coding more enjoyable.
You need to send data from one activity for another.
E.g.: you have a list of ToDo items, and open activity to edit one of them (so you have to pass data about selected item — at least it’s name and id).
Spoiler: it’s a good idea to use fragments and shared ViewModel, and I’ll explain how in following parts, but now let’s start with a simple example.
Solution without patterns:
Let’s solve this task as recommended in official documentation.
Code in target activity:
And how to start a SecondActivity:
Solution with IntentBuilder pattern:
So what’s the problem with the official solution? There are some:
First of all, you don’t specify extra type while setting it (putExtra()), but have to specify it while getting value (getStringExtra(), getBooleanExtra()). So if you use wrong type during setting extras (or change extra type in future and forget to change it in all your activities who called SecondActivity)— you’ll get a runtime error.
Let’s fix it using IntentBuilder class and passing values for extras in build() method returning instance of Intent class:
Ok. Now our code is type-safe — if you try passing wrong type of extra to SecondActivity, you get a compile time error.
We can improve syntax by creating separated set method for each extra.
Do we have any other problems? Yes. If some extras are mandatory (or you have another logic to check their correctness) — you can add check before putting extras in MainActivity. But if there are several entry points for your SecondActivity — you have to copy-paste your code. Let’s add start method to SecondActivity, which validates extras before starting activity by intent:
Now our code in SecondActivity looks more wordy than without patterns, but it’s easier to use it to start activity.
How use it in MainActivity:
That’s all! Happy coding :)