Google PlusTwitter

MVP for Android: how to organize the presentation layer

on Apr 15, 2014 in Blog, Development | 63 comments

Share On GoogleShare On FacebookShare On Twitter

MVP (Model View Presenter) pattern is a derivative from the well known MVC (Model View Controller), which for a while now is gaining importance in the development of Android applications. There are more and more people talking about it, but yet very few reliable and structured information. That is why I wanted to use this blog to encourage the discussion and bring all our knowledge to apply it in the best possible way to our projects.

What is MVP?

The MVP pattern allows separate the presentation layer from the logic, so that everything about how the interface works is separated from how we represent it on screen. Ideally the MVP pattern would achieve that same logic might have completely different and interchangeable views.

First thing to clarify is that MVP is not an architectural pattern, it’s only responsible for the presentation layer . In any case it is always better to use it for your architecture that not using it at all.

Why use MVP?

In Android we have a problem arising from the fact that Android activities are closely coupled to both interface and data access mechanisms. We can find extreme examples such as CursorAdapter, which mix adapters, which are part of the view, with cursors, something that should be relegated to the depths of data access layer .

For an application to be easily extensible and maintainable we need to define well separated layers. What do we do tomorrow if, instead of retrieving the same data from a database, we need to do it from a web service? We would have to redo our entire view .

MVP makes views independent from our data source. We divide the application into at least three different layers, which let us test them independently. With MVP we are able to take most of logic out from the activities so that we can test it without using instrumentation tests.

How to implement MVP for Android

Well, this is where it all starts to become more diffuse. There are many variations of MVP and everyone can adjust the pattern idea to ​​their needs and the way they feel more comfortable. The pattern varies depending basically on the amount of responsibilities that we delegate to the presenter.

Is the view responsible to enable or disable a progress bar, or should it be done by the presenter? And who decides which actions should be shown in the Action Bar? That’s where the tough decisions begin . I will show how I usually work, but I want this article to be more a place for discussion that strict guidelines on how to apply MVP, because up to know there is no “standard” way to implement it .

The presenter

The presenter is responsible to act as the middle man between view and model. It retrieves data from the model and returns it formatted to the view. But unlike the typical MVC, it also decides what happens when you interact with the view.

The View

The view, usually implemented by an Activity (it may be a Fragment, a View… depending on how the app is structured), will contain a reference to the presenter. Presenter will be ideally provided by a dependency injector such as Dagger, but in case you don’t use something like this, it will be responsible for creating the presenter object. The only thing that the view will do is calling a method from the presenter every time there is an interface action (a button click for example).

The model

In an application with a good layered architecture, this model would only be the gateway to the domain layer or business logic. If we were using the Uncle Bob clean architecture , the model would probably be an interactor that implements a use case. But this is another topic that I’d like to discuss in future articles. For now, it is enough to see it as the provider of the data we want to display in the view.

An example

As it is a bit lengthy to explain , I created an MVP example on Github consisting of a login screen that validates the data and allows access to a home with a list of items that are retrieved from the model. This article does not explain any code because it is quite simple, but if you see that you find it difficult to understand I may create another article explaining it in detail.

Go to MVP example on Github

Conclusion

Separating interface from logic in Android is not easy, but the Model-View-Presenter pattern makes a little easier to prevent our activities end up degrading into very coupled classes consisting on hundreds or even thousands of lines. In large applications it is essential to organize our code well. If not, it becomes impossible to maintain and extend.

63 Comments

  1. Stephen

    April 16, 2014

    Post a Reply

    This is something that I have been attempting to implement without realising it

    This is very useful and has definitely pointed me in the right direction.

    I would be interested in how to structure classes in an app where there is little ui and mostly services working in the background

    • Antonio Leiva

      April 16, 2014

      Post a Reply

      Services will be mostly domain layer. MVP only takes part in presentation layer, so there won’t be probably almost any relationship between them. If you need to feed the views with information from services, then I would use some kind of Observer pattern or event bus.

  2. marco

    April 16, 2014

    Post a Reply

    Do you think there is an advantage to adding the view through the constructor and having lifecycle methods in the presenter versus having the view add itself through a setter method in onResume and remove itself in onPause?

    • Antonio Leiva

      April 16, 2014

      Post a Reply

      I tend to add to it via constructor (injected in fact) and notify the presenter from the view when there’s is an event from the view that the presenter must be aware of. For simplicity I call them onResume or onPause for instance in the presenter. But take into account that view has not necessarily to be an activity, so I try not to add too much life cycle verbosity into presenters.

      • David Laurell

        April 18, 2014

        How do you inject the view into the presenter? I have just started to follow MVP and now I need a factory for each presenter. Do you do it in some other way?

        For example I have the following interfaces:

        public interface CalendarsPresenter {
        void addCalendar();
        void addPickedCalendar(Calendar calendar);

        void removeCalendar(Calendar calendar);
        void loadCalendars();
        }

        public interface CalendarsView {
        void showCalendars(List calendars);
        void showCalendarPicker(List alreadyChosenCalendars);

        void showLoadingIndicator();
        void hideLoadingIndicator();
        }

        And a Fragment that looks like this:

        public CalendarsFragment extends Fragment implements CalendarsView {
        @Inject CalendarsPresenterFactory mCalendarsPresenterFactory;

        private CalendarPresenterFactory mCalendarPresenter;

        @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        InjectUtils.inject(this);
        mCalendarPresenter = mCalendarPresenterFactory.create(this);
        }


        }

        Very nice approach clean and beautiful! :)

      • Antonio Leiva

        April 18, 2014

        I implement injection using Dagger. I create a Dagger module for each activity that injects the presenter and the view (usually the activity itself). If you decide to use Dagger, search about scope modules. They are very useful because they only live the time their scope is active, and memory is not filled with objects and singletons that won’t be used again.

      • marco

        April 18, 2014

        Thats exactly what I do, I get a reference to my global object graph and plus a short lived module to get extended graph.

      • David Laurell

        April 18, 2014

        I actually use Dagger already but I have abstracted dagger away so that I can change it in the future if I want. :)

      • David Laurell

        April 18, 2014

        But sure, I will search for scope modules! :)

      • Guicara

        June 4, 2014

        Can you provide a code example?

      • Antonio Leiva

        June 4, 2014

        Yes, you have some links at the post.

      • Guicara

        June 4, 2014

        Thank you, but do you have any code example about “injection using Dagger” (see your comment of April 18, 2014 )?

      • Antonio Leiva

        June 4, 2014

        No, not at the moment. I’m planning to write about it quite soon.

  3. Great article, I’m very interested in this area and I think more people should try to adopt these patterns.

    I guess one of the benefits of decoupling these layers would be easier testing (injecting dummy dependencies etc.), are you able to provide any insight to this aspect of MVP in android?

  4. sergiandreplace

    April 17, 2014

    Post a Reply

    Very interesting and a really useful example. This brings me a couple of questions, for example, how do you deal with a CursorAdapter? do you just stop using them? and how to deal with adapters at all? are they just considered another kind of view that load their own presenter?

    • Antonio Leiva

      April 17, 2014

      Post a Reply

      I don’t use Cursor Adapters, don’t like them because they don’t let me separate layers in a good way. I consider adapters as part of views, presenters don’t know anything about context or, in most of cases, Android SDK.

      • sergiandreplace

        April 18, 2014

        And how will you use it with an adapter? Will you make an specific presenter for the adapter row?

      • Antonio Leiva

        April 18, 2014

        No, presenter provides the activity the items, and it’s the activity who creates its own adapter. I don’t want the presenter to know that adapters even exists. If view changes, for instance I need to change my ListView and use a LinearLayout, the presenter doesn’t change.

      • sergiandreplace

        April 21, 2014

        Then i hava to do a couple of tests by myself :)

        Hard to see how to implement some things, but really this seems the right approach.

  5. i’m sorry for maybe stupid question, but is it necessary to create mvp-bunch for all android activity? If i have one login activity, list activity, another activity… i must create model, view and presenter for all of them?

    • Antonio Leiva

      May 6, 2014

      Post a Reply

      Sure, it should be that way. There are some cases where this structure is too much work for little benefit, so it’s up to you to decide where to use it.

  6. Cheng Wei

    May 18, 2014

    Post a Reply

    Hi Antonio, Good to see many people are interested on the topic. I would like to introduce our framework to you. You may be interested – RoboBinding(http://robobinding.org), A data-binding Presentation Model framework for the Android platform.

      • Cheng Wei

        May 25, 2014

        Hi Antonio, we are updating the docs for the project these days, but most of the docs are updated and transferred from the old docs now. We like to hear the feedback from you if there is any once you have had a look. whatever good or bad ones will be appreciated.

        Thanks,
        Cheng

  7. Martin M

    June 2, 2014

    Post a Reply

    Hi Antonio, I’ve been reading through your blog and I would like to adapt your MVP proposal for my Android app. I’m using the AsyncTaskLoader to fill my Views and now I would like to ask how you would implement Loaders in this pattern. Can you give me any suggestions?

    • Antonio Leiva

      June 2, 2014

      Post a Reply

      I wouldn’t. I use android-priority-queue from path for asynchronous interaction. My interactora are in fact jobs. That way, any domain interaction is performed outside the main thread.

      • Martin M

        June 12, 2014

        Hi, thanks for the response. Another question, how do you deal with content providers? I tried to seperate my app in 3 layers. (presentation, application and persistence) In order to call a content provider I need a Context object, do I have to pass it in at the presentation boundary and send it through the interactor to the database boundary? This seems to break all the seperation to me.

      • Antonio Leiva

        June 12, 2014

        Once again, dependency injection to the rescue. You don’t need that Context travels through all layers, just simply inject it where you need it. If you haven’t, read the articles I’m writing in this blog about DI and Dagger. There are already 2 out of 3 posts released.

  8. Sergio Correa

    June 9, 2014

    Post a Reply

    Hi Antonio, good post.
    I’ve just started looking through MVP and I have a question.
    In your example there is this part in the class MainPresenterImpl:

    @Override public void onItemClicked(int position) {
    mainView.showMessage(String.format(“Position %d clicked”, position + 1));
    }

    For instance, you decide to modify your view’s structure and want to show a custom dialog box that requires more information instead of a Toast message. In this case, what approach would you use ?
    1-Change the MainVew interface, adding parameters
    2-Leave the MainActivity responsible for it, without passing it to the presenter layer
    3-?

    Thanks

    • Antonio Leiva

      June 9, 2014

      Post a Reply

      You could change the implementation of showMessage in order to show a Dialog instead of Toast, and a call back to the presenter when the user clicks on an option to let the presenter decide the next step.

      • Sergio Correa

        June 10, 2014

        Actually, what I mean is the necessity of adding new parameters, for instance. I would have to change the MainView interface and Presenter implementation, not only MainActivity. In fact it’s related to View layer, but I would have to change my presentation layer as well. Just in doubt how far we should go to abstract the View layer job.

      • Antonio Leiva

        June 10, 2014

        Refactoring happens often. It’s difficult to foresee any possible changes, but you find those changes localized in a scoped and predictable place.

  9. sokol

    June 12, 2014

    Post a Reply

    I think that there is a problem.
    Architecture would be something like that:
    Delivery system : Activity, Fragment, Service and other Android related stuff. Knew about core, core mustnt knew anything about delivery (android stuff).
    Presenter lives on delivery side.
    – has a relationship of boundarie (interface) when calling Interactor (transaction, could be command pattern)
    – and implements boundarie interface on response of Interactor (Observer pattern).

    Core layer has:
    – Boundaries are interfaces:
    – Interactors implements them when request is made (transaction) from presenter.
    -or interactors trigger them (has a relationship) when response is made, presenters than implemets this boundaries interfaces.
    -Interactor is USE CASE of the application. It lives in CORE, not on a delivery side as in example and mustn knew anything about Android. So hier is a problem because Android must almost always do work in some kind of thread outside of Main UI thread.
    -Entity lives in core and represent business rules or business object (POJO) used by interactors. Entities dont knew anything about database, UI or Android.
    -Gateways (interfaces) lives in core and are responsable for handling database ( dao or repository).
    -Database layer: there are concrete implementation of gataways (dao, repositorie) and SqlLiteOpenHelper, SqlLiteDatabase or Content providers. Implemetation of dao-s with Android API.
    -Models or DTO objects can be for request and response data between layers.

    Once again how to separate Interactors that must be in core layer and are triggered from Presenter and have some kind of thread (mustnt knew about Android Looper, Handler or AsyncTask…)? And when thread is finished and result process how to get back result.

    • Antonio Leiva

      June 12, 2014

      Post a Reply

      Sure, as I said MVP is not itself an architecture pattern, and this example doesn’t try to implement any kind of layer architecture. As you said, interactors shouldn’t know anything about Android. There are ways to do threads only using Java, but even Android tools can be used by using dependency inversion. Core can use Android functions via interfaces and dependency injection. Your framework layer can implement an interface with the methods you need in your interactor. You could, for instance, wrap an AsyncTask with a core class, use that core class as the basis of asynchronous calls, and communicate back via Callbacks or an event bus.

  10. Patrick

    June 13, 2014

    Post a Reply

    And how will you use it with an adapter if the user can interact with a row (e.g. a button in the rows triggers a rest call)

  11. sokol

    June 13, 2014

    Post a Reply

    Thanks for the reply and clarification.
    I’ll try to do as you said. Good Blog with good examples.
    It ‘s quite difficult to have a good clean architecture and loosely coupled in Android.
    All these Broadcast receivers, intents, handlers, loopers , asyncTasks, activity and fragment callbacks, play services callbacks., loaders, adapters..
    It’s hard to achive separation of concerns. I’m wriiting Android application for my diploma (maps v2, activity recognition, fused location providers, geofences, some kind tracking app with background services…) and I would like to have clear architecture as uncle Bob suggest, but its hard, verry hard. To much wrappers, interfaces, houndreds of small classes and interfaces.
    I have already wrote this app. It worked but it was a code mess. Now I’m completly rewritting this app with better architecture in mind and abstractions, patterns… I would like to write an app in core layer with Robolectric tests and then the other stuff UI, DB (which I already have from before).

  12. Patrick

    June 14, 2014

    Post a Reply

    Could you please explain, how you implement MVP with an adapter? I’m very interested in your approach…

  13. Antonio Leiva

    June 14, 2014

    Post a Reply

    No problem! It depends on the project, but I use Retrofit and OkHttp whenever I can. Retrofit is magic :)

    • Patrick

      June 17, 2014

      Post a Reply

      How are you using your MVP approach when your are dealing with Fragments? Has every Fragment it’s own MVP classes or are Fragments “views only” and they get their data and behavior over the presenter from the parent activity?

      • Antonio Leiva

        June 17, 2014

        I use the second approach almost always. But there are places where the first approach fits better, for instance in fragments related to navigation drawer options.

      • Patrick

        June 18, 2014

        Ok thanks, sounds great! Are you using any testing frameworks? Could you maybe post test cases for the login module in your MVP example?

  14. Boy Lenssen

    June 28, 2014

    Post a Reply

    I do not see the difference with MVC just yet…I used an MVC approach before, and I noticed that having a man-in-the-middle (controller/presenter) bugging me. Adding/changing something just gave me extra work, as I ALWAYS had to change the activity and controller…
    I just keep everything in the activity and big things in separate classes to be handled if it is generic…

    I think I might be wrong, but I did not find a way for this to contribute to my Android development…speed nor clear readable code

    • Antonio Leiva

      June 29, 2014

      Post a Reply

      The concepts are very similar. We could call it MVC if we used the activity as controller, but we are considering part of the view here, so the user interaction goes directly to View (activity) and not to the middle-man. Separation of concerns give lots of advantages in terms of testing, reusing and modifying when working in a project where the scope is changed easily. From my experience, it’s also much easier to detect when bugs are, because layers are well defined and every one has its own responsibilty. Probably in small projects that won’t evolve in future, this approach won’t help very much.

      • Patrick

        June 29, 2014

        Could you maybe post a more complex example of your mvp approach (e.g. with adapters, custom views, fragments…)? I would be very helpfull to umderstand how things work together.

  15. Hi there,

    I’m not convinced by your implementation.

    First of all: thanks for sharing this and for starting this important discussion.

    Your code is very clean and, from a java standpoint is perfectly fine.
    Still, it doesn’t take into account the activity lifecycle at all.

    Specifically: your implementation use an Handler to perform the login notifying an interface when done.
    While the login is performed in background multiple things can happens to your activity:
    A) it can be destroyed to be recreated (cause the user rotated the device / cause an incoming call has come or the user switched activity)
    B) it can be destroyed cause the user exit the app tired to wait.

    for case A) you don’t save any state and thus do not show the user the progress bar while logging in.
    The user may click again for login of be puzzled by that.

    And if an error occur you do not show it to the user because the notification reach the previous activity.

    for case B) the user close the activity but if the login is successful the app open the new activity anyway.
    Picture the user interaction:

    1. click login
    2. back to close
    3. hey it opened again even if I closed it

    Furthermore, since your interface is actually a reference to the activity you are creating a memory leak while the background process is running you may keep an already destroyed activity in memory until the login is completed.

    To properly handle stuff like this you need to make the background process completely separated of the activity and have a way to re-attach to it with your activity when the process resume.

    In short: what a Loader do in Android.

    But if you add the loader to the picture everything becomes lot more complicated.

    I’m not saying MVP is wrong. I just say that is harder to develop *right* with it in Android then in other system. Because of how the framework and the app metaphor is build.

    I would really like to apply a decoupling like that but I don’t see a way to do it taking into account the Activity Lifecycle without making it overly complicated. Any idea?
    I’m curious to hear what you and the community think about this.

    • Antonio Leiva

      July 3, 2014

      Post a Reply

      Hi Daniele. You are right, but this is a simplified version with its obvious drawbacks. What I do is using an event bus to decouple interactors from presenters. Presenter subscribes to bus when its view resumes and unsubscribes when it pauses, so in an orientation change it will receive the response previously performed. You will also need to save current status to let the recreated activity know that a login operation is currently executing, as you mentioned. Apart from that, I think any other problem you mentioned is solved. As in a loader, you are dettached when activity pauses an reattached when it resumes.

      • Antonio Leiva

        July 3, 2014

        Yes

      • Daniele Segato

        July 3, 2014

        I see!

        I’ll try it out.

        Anyway, if you are willing to take a suggestion from me, I would write in your article / readme in the github that the example doesn’t take into account different thing in the activity lifecycle and that is only meant to show how an MVP is.

        And may be add the comment you wrote in reply to me as a suggestion on how to implement it correctly in Android.

        Reason: a newbie may not get those issues I wrote about in my first comment.

        Thank you again for your article and responses.

  16. Kasper

    July 10, 2014

    Post a Reply

    How do you handle Android activity recreations using the MVP pattern? The activities should be recreated in the state that they were left. For example, if an android device is rotated while the LoginActivity in your github example project is currently testing if user credentials are correct, progress will be lost.

    The same could apply for more complex views where data needs to be loaded. For example, the MainActivity in your example recreates the Presenter when it a user rotates his device. If the items were loaded before rotating the device, then they will be reloaded when it is rotated, which may confuse the user!

    How do you handle these “activity requirements” imposed by Android?

  17. Eugene Beletskiy

    September 8, 2014

    Post a Reply

    Nice post, thanks for it!

    So what do you finally test? Do you test all those components including Views separately? So you test View, Presenter and Interactor?

    If we look at LoginPresenterImpl for example, what do you test here? Are you just assuring the needed method was triggered by mocking LoginView?

    Can you just briefly describe _what_ you test in these separations?

  18. Will Benedict

    September 12, 2014

    Post a Reply

    Interesting, and well worth discussing. Some observations:

    1) As Model often refers to some ball of data (smart or dumb) that is persisted or serialized (a fancy struct) in architectural discussion, I prefer the term Interactor (as does your code). I understand it’s a reference to MVC, but…it’s a confusing term in this context.

    2) The Interactor is a business class like any other. The pattern is effectively this: View Presenter —> Business.

    3) What value to the interfaces provide that couldn’t me more easily provided by javadoc and Mockito?

    4) The View and Presenter are very tightly coupled, to the point where they each have a reference to one another. They could easily be the same class with no loss of organization and significantly less boilerplate. The value is in forcing developers to consider the separation of the two most common concerns (view/presentation) instead of writing them as a few giant method in an Activity or Fragment.

    There is real value there, but it will still be very difficult to break a large Fragment or Activity down more than the (roughly) half this pattern provides without new ideas. The only thing I’ve come up with to further break down monster Activities/Fragments is UI-based util classes. Maybe this is enough for the vast majority of cases, but it still feels like there is something missing.

  19. Arnaud

    November 19, 2014

    Post a Reply

    Hi,

    I was wondering if we should limit ourselves to having one Presenter for one View and one View for on Presenter ?
    I have a case where my View consist of an ActionBar and a ViewPager ( handled by a custom PagerAdapter that creates the Views ).
    In the constructor of my Views I have some initialization things I do such as loading images via http and so on. Now my solution would be to inject the Presenter that my Activity deals with in my View ( from the pager ) so that I could call something like this.presenter.requestImages(). But I still have one issue remaining, the presenter will provide it through my Interface implemented by the Activity, which should then provide it to the adapter which should retrieve the appropriate view ( how ? ), and then set it. It seems like 3 levels to go through, with a lot of boiler plate to keep track on which view in the pager actually requested images.

    What would be the good approach to organize this kind of View ? My structure is like this :
    – Activity implements IView
    – PagerAdapter
    – View[] : How do I deal with the presenter from here ?

  20. Chan Mok Jeon

    November 20, 2014

    Post a Reply

    Hello,

    This is very interesting post. I am a new to MVC/MVP pattern for android. I am trying to use this pattern for my code. But I faced two problems in my code with this pattern.

    You mentioned that the only job that the view does is calling a method from the presenter when there is an interface action, such as onClick, onClose, onPause, etc. But do we consider onCreate() method as an interface action as well?

    So I have a several variable initializations in Activity and they are relying on the data from intent. So when the Activity gets created, it initializes some variables with the Intent data and launches either dialog A or B depending on the initialized variables. Then should I have the initialization method in presenter and call it from onCreate in Activity? Or should I put the method in presenter and call it from presenter’s constructor? What would be the ideal in this case?

    Also, I get the intent data by calling getIntent() method in Activity. So the method needs to take Intent as parameter. I can see one possible ways handle this. One way would be creating a method in View and call getIntent() in that method for Activity implementation. Then, we can call that method from presenter. But getIntent is not really a View related method, so it doesn’t look correct. Can you help me to find the ideal way to handle this?

    Thanks!

  21. Chan Mok Jeon

    November 22, 2014

    Post a Reply

    I have another question. I found that you shared two examples in GitHub.

    In MainActivity, onItemClick method calls presenter.onItemClick(position). Then, in presenter, onItemClick method calls mainView.showMessage(…).
    So in this example, you are not putting any logic in MainActivity at all. It is simply calling onItemClick method so MainActivity doesn’t need to know what onItemClick will do.

    In LoginActivity, onClick method calls presenter.validateCredentials(username.getText().toString(), password.getText().toString()).
    While MainActivity doesn’t know what is going to happen on item click, LoginActivity knows that when user clicks, it will begin to validate credentials.

    If we wanted to avoid this consistency, we could replace presenter.validateCredentials(..) with presenter.onClick() in LoginActivity and add mainView.getUsername() and mainView.getPassword() in LoginView. So in presenter, onClick method can call validateCredentials(mainView.getUesrname(), mainView.getPassword()).

    I am not sure which one to follow. First one makes more sense to me because I don’t want View to know anything other than performing UI actions. But then I will have to create too many getters in View when presenter needs to know more resource information.

    If I follow the LoginActivity version, I need to put the detailed responses for every user action, but I can avoid having getters.

    What is your thought on this?

Trackbacks/Pingbacks

  1. Dependency injection on Android: Dagger (Part 1) | Antonio Leiva - […] will be a follow-up from my previous post about MVP for Android, because I know some of you are …
  2. 整理Android Weekly上的资源 | 我爱互联网 - […] MVP for Android: how to organize the presentation layer […]

Leave a Reply