Android and Handling Configuration Changes with MVP

Firstly I’d like to start by briefly saying, I’m new to Java and Android development and welcome any constructive criticism that this post may throw up. I’m not going into too much details of the intricacies of everything mentioned as that would make this post waaaay too long!

Right now that’s out of the way I’d like to talk about something that I have found very useful when approaching Android app development - The Model View Presenter pattern.

When I started looking at tutorials for Android apps I found it very exciting and really loved getting to grips with the basic coding and Android frameworks. As I started to deviate from the tutorials and implement my own (basic) apps I soon ran into more and more problems. One of the major ones was handling screen rotations (configuration change) whilst performing long running tasks like network calls via Android’s AsyncTask. Any Android developer will tell you Activities have a life-cycle and when the screen is rotated the Activity is destroyed and recreated, so any references to the old Activity will be null, and can easily cause memory leaks and null object references (I think I said that correctly!). Having looked at ways to handle this I first looked into Headless fragments, and the key with this being:

setRetainInstance(true);

This allows the fragment to be ‘retained’ when the Activity it is attached to is destroyed and recreated. Great problem solved! I can handle all my logic within the headless fragment, calling back to the Activity as needed, regardless of configuration changes. This is fine, however it felt like my code was still closely connected to the Activity where portions of code would be in the Activity and some in the retained fragment .. it all seemed a bit ‘messy’.

Having looked around for a while I came across an Android implementation of the Model View Presenter pattern (MVP for short). The idea behind this being to have clear separation layers between your View (Activity) and Model layer (network calls/database calls etc) with the Presenter sat between them - more info:

https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter)

basic sketch I made of MVP Pattern I wanted to implement

I would urge anyone who develops for Android to have a look into the MVP pattern. Every time that I create an app all the complexity and headaches that can arise from configuration changes go away. I have a small app on github that uses an implementation of the MVP that is heavily based upon examples of the MVP pattern I have seen (my code is commented, so hopefully tracing through it should be straight forward):

https://github.com/TreeFrogApps/A3_WeatherService