Avoid the Android Activity Spaghetti Monster
When I first started building Android applications, I was in a hurry to learn (deadlines!), so I went about it the quick and dirty way: I googled for answers and followed the examples I found in the Android SDK documentation.
It was enough to make progress and write shippable code, so everybody was happy.
Unfortunately, as the application I was working on kept growing, the structure suggested by the Android SDK became too limiting. Putting all the code in activities was getting messy really fast, and I was ashamed of how it was turning out. Everything depended on every other thing, a lot of logic was in the UI and it was harder and harder to add new functionalities or modify the layout without rewriting large chunks of code.
How can you tame this beast and take control of your application?
First, you must realize that the situation is not your fault, and that many developers have been tripped up by this. In most other frameworks, like Ruby on Rails and Laravel on the web, you will be directed subtly (or not so subtly) on the path to a decent architecture with templates and conventions.
But with the Android SDK, the all-powerful Activity will get in your way. Activities basically try to do everything at once:
When looking for something better, the default answer is to use one of the most popular application design patterns, Model-View-Controller, or MVC for short. An application patterns tells you how to structure your code in various parts, such as:
But if you try to untangle your Android applications by following that pattern to the letter, you won't see much progress because the activity will get in your way. You will end up with a Model representing a few objects and the database access, and everything but the kitchen sink in the activity (the view, the controller and all the work beside the definition of the layout).
Fortunately, there is another pattern better suited to the constraints of the Android SDK, Model-View-Presenter, or MVP for short :
This will allow you to put your Activity back in its proper place, as the class driving the interactions with the user. You can then move a lot of application logic outside of your activity and structure it.
Unfortunately, there are no tools or classes in the Android SDK that will guide you and help you do this, and it involves touching all the parts of your application.
That's why I'm building a course to demonstrate how an application built using the Model-View-Presenter pattern looks like.
I'll take a TODO list application from an Activity-centric architecture, to an MVP architecture.This way, you can follow along and then refactor your own application without starting from scratch, or follow along and learn about which pitfalls you must avoid.
Sign up below and so I can keep posted about my progress.
This course is still a work in progress. Sign up to my newsletter to be notified when it launches.