MVP for Android

Have you ever had problems with the lifecycle of an Activity or Fragment? The necessity to handle things like a configuration change, an activity kill because of low memory issues, removal of the entire app process, etc. always distinguished Android mobile enviroment from other application runtime enviroments.
In our Android world there are many platform specific factors that we should pay attention to while writing every single line of code and especially during a development of libraries/frameworks.

The same is the case when we want to use any architectural pattern…

For a long time I was looking at the Model View Presenter topic for an Android with some distance. Not MVP just as a pattern, because it’s clear that every responsibility separation is great, but primaily its implementation in an Android way.


I begin my analysis of the Presenter part of MVP model by adopting following assumptions:

  • We will use Presenters in our system components (Activities or Fragments)
  • Presenters should live in the memory only as long as the components they belongs to:
    • The Presenter should be retained on configuration changes – i.e. if we want to retain long running tasks (even if an activity is being recreated in the same moment)
    • The Presenter should be destroyed if a related component like activity or fragment is destroyed, either because of memory running out problem or just because of user action – we don’t want to needlessly waste memory and store presenter in memory if related activity/fragment is currently not there
    • The Presenter should be recreated after process recreation (if proces of our app was killed because of low memory issues) – we must ensure reliabilty and possibility to restore presenter state later even if proces is destroyed
  • A presenter implementation should impact on the other components code in the least possible way

Possible options

Having those assumptions we could think of our proper MVP implementation. First conspicuous and most problematic thing is proper presenter preservation in combination with the Activity/Fragment lifecycle.

I collected possible implementations solving this problem and I will describe them briefly:

  1. Save the Presenter state in a Bundle
    The first implementation on this list which makes any sense. Use onSaveInstance bundle to save the Presenter state and later recreate it.


    • Pretty simple
    • We could save and recreate the presenter state in the bundle object (on configuration changes or process recreation)


    • We could not retain long running tasks because on the activity recreation our task will be restarted (or will leak activity/fragment if we not kill or detach it from our component)
  2. Use a Fragment with setRetainInstance

    Presenter could be stored inside the Fragment with a flag setRetainInstance set to true.


    • We could save and recreate the presenter state in a Bundle object
    • We could retain long running tasks because they retain the configuration change same as the retained Fragment


    • We could not use this option if we want to implement an Activity only solution
    • setRetainInstance Fragment could not be
      • used as a child fragment
      • used properly on the back stack
    • setReitanInstance Fragment should not contain any references to views because of potential (view/context/activity) memory leak issues
  3. Retain a presenter using Activity onRetainCustomNonConfigurationInstance method

    We could store presenter references inside an object retained via onRetainCustomNonConfigurationInstance method


    • The Presenter state retained between config changes
    • We could retain long running tasks


    • The method available only for activities, could not be used with fragments
  4. Hold presenter in some static singleton

    Simply store the presenter reference inside some static storage, i.e. a map of presenters


    • We could save and recreate the presenter state in a Bundle object
    • We could retain long running tasks because they live as long as application process


    • Presenters should live in a memory only as long as its component (Activity/Fragment) is in memory. Using a static map we are changing the scope of responsibility.
      There is a possibility that activity will be removed from memory because app needs its in other place, but the presenter for that activity will still be in the memory held by some static references. This is an unnecessary waste of the memory.
    • Static fields are bad
  5. New method!
    Save and retain a presenter inside the Loader object
    We could use the Loader retaining mechanism to store our Presenter. This method works universally both for activities and fragments.


    • The Presenter retained between config changes
    • We could retain long running tasks
    • We could recreate a presenter even if the whole proces will be recreated
    • An independent usage in an Activity or Fragment.


    • Loaders are not so popular – but using my helper library for this make this problem negligible


You can see that there are a lot of methods to deal with Presenter retain. To make comparision easier to visualise I created a table with all presented options:

Android MVP - Presenter retain comparision

We could easily notice that last implementation using Loader to retain meets all of our assumptions from the beginning and looks like the best choice (and as you will see later – also easy) to implement.

Originally this ‘Loader’ idea is not mine. It was suggested by Ian Lake (Google Dev) as an answer to my question in one of Google ‘Developer Show’ series video:

We’ve got the winner

Now you can scratch your head and ask ‘Loader? I don’t know what it is?’.

I’m aware that many people don’t use or don’t know loaders because at first glance they may look strange and there are some issues with them in specific situations.

In response to the following reaction I created library called Tomorrow!


To help all of you in MVP pattern with loaders (to retain presenters) implementation without even knowing or having any idea how loaders really work.
Tomorrow MVP library and its full description/documentation is available on GitHub and also as a dependency on maven server.


Fragments – every day tips

#Tip 1 – static newInstancemethod pattern

Note: Avoid setter methods and parametrized constructors to modify fragment state, because platform uses only default (0 parameter) constructor, arguments bunde and saved state bundle to restore it later.


#Tip 2 – single fragment in Activity

If your activity role is only to show fragment don’t create custom layout with container to add your fragment. Use default activity root container identified by


#Tip 3 – nested/child fragments will not get onActivityResult callback

Activities started with startActivityForResult will automatically call onActivityResult on ‘first level’ (added directly to Activity FragmentManager) Fragments.
If you want to use activity result mechanism with child fragments, you have to pass this callback on your own.


#Tip 4 – Use setRetainInstance(true) only in non-UI fragments

setRetainInstance(true) method will ensure that your fragment will survive orientation changes and its activity recreation. Using this flag in Fragments with UI/widget/view references could potentially cause memory leaks, like this:

After orientation change and before second onCreateView TextView reference will hold old view with all it’s context – which is an old Activity. This means two Activities in memory at the same time, one new and one old held because of this TextView reference until mMyTextView = (TextView) root.findViewById(; will not be called again


#Tip 5 – setRetainInstance(true) cannot be used with nested/child fragments

If you try to use this flag in your child fragment you will get exception java.lang.IllegalStateException: Can't retain fragements that are nested in other fragments


#Tip 6 – Custom attributes on XML initialized fragments

If you want to create fragment via XML layout, you could declare custom style attributes and read them later in onInflate (Context context, AttributeSet attrs, Bundle savedInstanceState)


#Tip 7 – Debug your fragment

If you want to check what is the current state of FragmentManager and it’s fragments just use FragmentManager.dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) method like this:


#Tip 8 – Prefer over

Fragments packed into v4 support library are created on newer code. Support library could receive faster updates and bugfixes in contrast to which is a part of Android framework released with different version on different devices (with a small probability of receiving updates).


Fragments restoration magic (mechanism)

In my last post, where I described a problem of incorrect usage of Fragments instantiation inside FragmentPageAdapter & ViewPager, I wrote:

After orientation change all fragments currently added to FragmentManager are automatically restored and instantiated so there is no need to create them once again.

Today, I want to focus more specifically on an issue how this automatic restoration works under the hood.


The simplest way to use a fragment:

A custom fragment instance is created and added to FragmentManager with help of FragmentTransaction.
We could add that our Fragment will be added to container identified by

This is the easiest case. I want to point out that we are not using setRetainInstance(true) inside our custom fragment implementation, and our activity is not protected in manifest agains any type of configuration changes.

The Question

Now, what will happen with our fragment if suddenly our device configuration will change, i.e. orientation?

Android Source Code (especially FragmentActivity and FragmentManager/FragmentManagerImpl) is a place where we should look for the answer.

1. Saving the state

Before Activity will be destroyed itsonSaveInstanceState method will be called. Take a look what this method is doing internally.

It takes mFragments (reference to FragmentManager held in this Activity) and callsFragmentManager.saveAllState() method which will return a parcelable object ready to be saved inside the bundle which, you can already guess… later will be used to restore Fragments.

In reality result of saveAllState method call is an object of typeFragmentManagerState which consists of information about all active fragments and back stack entries

Last quick look at FragmentState.

It consists of all data which describes a specific fragment object instance, like container id, tag, arguments but also savedFragmentState.

It looks sufficient to create fragments from scratch, and set them like they were before.

2. Destroying fragments and activities.

After state of fragments is saved via FragmentManager activity object is destroyed (removed from memory) with all its fragments (those which are not retained with setRetainInstance(true)).

3. Creating activity and recreating fragments

Final point is a recreation of the activity and recreation of the fragments. It starts within the first Activity lifecycle callback method onCreate(Bundle savedInstanceState)

The previously saved fragment manager state bundle now is used inside FragmentManager.restoreAllState method. This metod declaration is quite long but I want to focus on the most important part.

Array with all FragmentState objects is iterated. And every FragmentState object is used to recreate (create new instance with state like before) specific Fragments.

A new instance of a fragment is created by platform with usage of reflection and default constructor – that’s why you must remember to always ensure the existence of public non-argument fragment constructor and initialize your fragment through arguments bundle (not with usage of fragment object setters from strange places).

This is short story how restoration of Fragments works.


Points to remember:

  • Already created fragments are restored automatically after orientation change
  • Magic behind this is just code written in Activity together with FragmentManager logic/implementation
  • Avoid setter methods and parametrized constructors to modify fragment state, because platform uses only default (0 parameter) constructor, arguments bundle and saved state bundle to restore it later
  • Fragments are not so bad

Fragments in ViewPager

Using ViewPager with FragmentPagerAdapter or FragmentStatePagerAdapter appears to be quite easy and enjoyable.

It could be done within few simple steps:

  1. Create layout .xml resource with ViewPager
  2. Create adapter and implement all required methods
  3. Set adapter instance to your ViewPager instance.

Simple? Yes! – but like always only for easiest (also the most common) case

Problem occurs when we want to make something more sophisticated, i.e. add fragments dynamically – provide fragments/pages to adapter from its outside.

The Code

Take a look at quite popular AppIntro library. It gives user a possibility to simply create an app intro just by extending  one AppIntro Activitiy.
One extend, few Fragment slides added in init method, and we got it!

So…the idea of this AppIntro library is to separate and take off weight from a developer to manage all those adapters and viewpagers.

Look in the source code can bring us closer to a basic concept (as I could only imagine it) of this library

Every activity onCreate() callback method calls init(savedInstanceState) method to give a user possibility to add fragments/slies which later are used in FragmentPagerAdapter class.


So it looks like all good at the beginning, but yellow light may light up in the head of the developer.


Creating/providing new fragments instances every time in onCreate() method.

Do you remember what we are doing when we want to create and just add single a fragment to our Activity?

We are checking if this is the first run or recreation after a configuration change.

After orientation change all fragments currently added to FragmentManager are automatically restored and instantiated so there is no need to create them once again.

Same thing is with the ViewPager and FragmentPagerAdapter. Once the adapter adds a fragment to FragmentManager after rotation it will not call getItem(int position) adapter method, but it will look for an already recreated Fragment in FragmentManager.

Line 11 – finding from manager, and only if the fragment is not yet there Line 16 gets new fragment instance from getItem() method



We should always remember about the automatic fragment restoration process done via FragmentManager with companion of Activity implementation.

Provide fragments only once at the beginning or only when they are needed (in case of an adapter and getItem(int position) method call) not every time redundantly.