Avoid the Android Activity Spaghetti Monster
You can build a few Android applications merely by following the examples that ships with the Android SDK, cobbling together something that works. It's good to learn how everything fits at first, and everybody will be happy with how the application turned out.
But when you take the next step and start to build applications that have more than one screen, you realize that putting everything in your activities gets messy really fast.
As your application grows, you start being ashamed of how your code turned out, with everything depending on every other thing. It gets harder and harder to add new functionalities or modify the layout without rewriting large chunks of code.
How can you tame the 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:
The default answer when trying to add some structure to an application 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 :
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 with a class or two to access the database or other services, 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.
This course is still a work in progress. Sign up to my newsletter to be notifed when it launches.