MVP for Android: how to organize the presentation layer

[et_pb_section admin_label=”section”]
[et_pb_row admin_label=”row”]
[et_pb_column type=”4_4″][et_pb_text admin_label=”Text”]MVP (Model View Presenter) pattern is a derivative from the well known MVC (Model View Controller), and one of the most popular patterns to organize the presentation layer in Android Applications.

This article was first published in April 2014, and been the most popular since then. So I’ve decided to update it solving most of the doubts people had, and also convert the code to Kotlin.

There have been breaking changes about architectural patterns since then, such as MVVM with architecture components, but MVP is still valid and an option to take into account.

What is MVP?

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

The first thing to clarify is that MVP is not an architecture by itself, it’s only responsible for the presentation layer. This has been a controversial assessment, so I want to explain it a bit deeper.

You may find that MVP is defined as an architectural pattern because it can become part of the architecture of your App, but don’t consider that just because you are using MVP, your architecture is complete. MVP only models the presentation layer, but the rest of layers will still require a good architecture if you want a flexible and scalable App.

An example of a complete architecture could be Clean Architecture, though there are many other options.

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 UI and data access mechanisms. We can find extreme examples such as CursorAdapter, which mixes 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 lets us test them independently. With MVP we take most of the 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 to their needs and the way they feel more comfortable. It varies depending basically on the number 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 rather than strict guidelines on how to apply MVP, because up to there is no “standard” way to implement it.

For this article, I’ve implemented a very simple example that you may find on my Github with a login screen and a main screen. For simplicity purposes, the code in the article is in Kotlin, but you can also check the code in Java 8 in the repository.

The model

In an application with a complete layered architecture, this model would only be the gateway to the domain layer or business logic. If we were using Uncle Bob’s clean architecture, the model would probably be an interactor that implements a use case. But for the purpose of this article, it is enough to see it as the provider of the data we want to display in the view.

If you check the code, you will see that I’ve created two mock interactors with artificial delays to simulate requests to a server. The structure of one of this interactors:

class LoginInteractor {

    ...

    fun login(username: String, password: String, listener: OnLoginFinishedListener) {
        // Mock login. I'm creating a handler to delay the answer a couple of seconds
        postDelayed(2000) {
            when {
                username.isEmpty() -> listener.onUsernameError()
                password.isEmpty() -> listener.onPasswordError()
                else -> listener.onSuccess()
            }
        }
    }
}

It’s a simple function that receives the username and the password, and does some validation.

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. The 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 presenter method every time there is a user action (a button click for example).

As the presenter must be view agnostic, it uses an interface that needs to be implemented. Here’s the interface that the example uses:

interface LoginView {
    fun showProgress()
    fun hideProgress()
    fun setUsernameError()
    fun setPasswordError()
    fun navigateToHome()
}

It has some utility methods to show and hide progress, show errors, navigate to the next screen… As mentioned above, there are many ways to do this, but I prefer to show the simplest one.

Then, the activity can implement those methods. Here I show you some, so that you get an idea:

class LoginActivity : AppCompatActivity(), LoginView {
    ...

    override fun showProgress() {
        progress.visibility = View.VISIBLE
    }

    override fun hideProgress() {
        progress.visibility = View.GONE
    }

    override fun setUsernameError() {
        username.error = getString(R.string.username_error)
    }
}

But if you remember, I also told you that the view uses the presenter to notify about user interactions. This is how it’s used:

class LoginActivity : AppCompatActivity(), LoginView {

    private val presenter = LoginPresenter(this, LoginInteractor())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        button.setOnClickListener { validateCredentials() }
    }

    private fun validateCredentials() {
        presenter.validateCredentials(username.text.toString(), password.text.toString())
    }

    override fun onDestroy() {
        presenter.onDestroy()
        super.onDestroy()
    }
    ...
}

The presenter is defined as a property for the activity, and when the button is clicked, it calls validateCredentials(), which will notify the presenter.

Same happens with onDestroy(). We’ll see later why it needs to notify in that case.

The presenter

The presenter is responsible to act as the middleman between view and model. It retrieves data from the model and returns it formatted to the view

Also, unlike the typical MVC, it decides what happens when you interact with the view. So it will have a method for each possible action the user can do. We saw it in the view, but here’s the implementation:

class LoginPresenter(var loginView: LoginView?, val loginInteractor: LoginInteractor) :
    LoginInteractor.OnLoginFinishedListener {

    fun validateCredentials(username: String, password: String) {
        loginView?.showProgress()
        loginInteractor.login(username, password, this)
    }
    ...
}

MVP has some risks, and the most important we use to forget is that the presenter is attached to the view forever. And the view is an activity, which means that:

  • We can leak the activity with long-running tasks
  • We can try to update activities that have already died

For the first point, if you can ensure that your background tasks finish in a reasonable amount of time, I wouldn’t worry much. Leaking an activity 5-10 seconds won’t make your App much worse, and the solutions to this are usually complex.

The second point is more worrying. Imagine you send a request to a server that takes 10 seconds, but the user closes the activity after 5 seconds. By the time the callback is called and the UI is updated, it will crash because the activity is finishing.

To solve this, we call the onDestroy() method that cleans the view:

fun onDestroy() {
    loginView = null
}

That way we avoid calling the activity in an inconsistent state.

Conclusion

Separating interface from logic in Android is not easy, but the MVP pattern makes it easier to prevent our activities end up degrading into very coupled classes consisting of hundreds or even thousands of lines. In large Apps, it is essential to organize our code well. Otherwise, it becomes impossible to maintain and extend.

Nowadays, there are other alternatives like MVVM, and I will create new articles comparing them and helping with the migration. So keep tuned!

Remember you have the repository, where you can take a look at the code in both Kotlin and Java

And if you want to learn more about Kotlin, check the sample App of my Kotlin for Android Developers book, or take a look at the online course.[/et_pb_text][/et_pb_column]
[/et_pb_row]
[/et_pb_section]

174 thoughts on “MVP for Android: how to organize the presentation layer”

  1. 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

    1. Antonio Leiva

      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.

      1. Take one scenario where the View layer is not active (App is in background) and , a Notification update is required from the service (In the notification tray , such as a download progress) , what is the best way to do this? Since the notification update is a UI operation , is it recommended to construct and show the notification from the service itself? Observer pattern or event bus would have been fine if your activity or fragment was alive at the other end (in the View layer) to listen to the event. So , in this case creating and showing a UI component from the domain layer (Service) will break the MVP conventions?

      2. In that case, you can consider the notification as an external component you communicate with, instead of a UI component. The service could interact with a component that “notifies changes”. The real implementation would just show or update a notification. If tomorrow you also need to notify to another service (let’s say firebase or your own server), everything can be tackled from there without changing the rest of the code.

  2. 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?

    1. Antonio Leiva

      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.

      1. 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! 🙂

      2. Antonio Leiva

        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.

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

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

      5. Antonio Leiva

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

      6. You’re reading an article that’s two years old, it’s obviously out of date… BTW, this article is related to MVP and not Dagger, the ideas are still valid, and Dagger is just mentioned, not even used in the example.

  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. 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?

    1. Antonio Leiva

      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.

      1. Antonio Leiva

        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.

      2. I think adapter row is better to be mapped to a presenter(presentation model or view model), especially when the row layout is complicated, for a clear separation. If you are interested, you can take a look at an example here – https://github.com/RoboBinding/RoboBinding/blob/develop/album-sample/src/org/robobinding/albumsample/presentationmodel/AlbumItemPresentationModel.java. Album-sample is an android rewrite(based on RoboBinding) of Martin Fowler’s original one.

  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?

    1. Antonio Leiva

      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. 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.

      1. 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. 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?

    1. Antonio Leiva

      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.

      1. 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.

      2. Antonio Leiva

        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.

      3. hi Antonio, I’ve been reading through this post and this particular comment confused me. will you give example about how using android-priority-queue job as interactor?
        thanks

  8. Sergio Correa

    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

    1. Antonio Leiva

      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.

      1. Sergio Correa

        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.

      2. Antonio Leiva

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

  9. 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.

    1. Antonio Leiva

      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. 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. 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. Could you please explain, how you implement MVP with an adapter? I’m very interested in your approach…

    1. Antonio Leiva

      I just consider it part of the view. The presenter will provide the items to be shown in the list. The view will then create an adapter and subscribe to onItemClickListener. Presenter will be informed when an item is clicked.

      1. OK thanks for your reply. Are you using a EventBus library in your apps? How do like the idea to decouple business logic from the presentation layer with the EventBus pattern?

      2. Antonio Leiva

        Yes, I use Otto. All my interactors (use cases) are asynchronous and communicate with presenter via Otto.

      3. Nice and what library are you using for your network layer? Volley, Ion, RoboSpice…? Sorry for all the question but structuring Android apps is a really interesting topic and I like to talk to other developers how they do that.

    2. Hi Patrick, our framework RoboBinding provides a way for dealing with adapters and adapter row, which you might be interested to have a look – http://robobinding.github.io/RoboBinding/getting_started.html#_binding_with_adapterviews. RoboBinding treats Array, List and CursorAdapter the same as data sources. there is an example here for CursorAdapter – https://github.com/weicheng113/robobinding-gallery/blob/master/src/org/robobinding/gallery/presentationmodel/TypedCursorPresentationModel.java.

  13. Antonio Leiva

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

    1. 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?

      1. Antonio Leiva

        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.

      2. 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. 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

    1. Antonio Leiva

      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.

      1. 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.

    1. Antonio Leiva

      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.

      1. 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. 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. 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. 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.

    1. I agree with Will. Looking over the Github sample for MVP Example, all I see is a bunch of unnecessary classes and interfaces. So when multiple developers touch this code and do pull requests, it will be a pain to review the changes in so many files. Less code can be achieved with good Javadoc and Mockito + Dagger.

  19. 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. 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. 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?

  22. Great example! I used your MVP to set a list of items in a Spinner. My Model deserialized data from JSON and builds ArrayList of String. The Presenter gave the Spinner in my View a way to setAdapter with a setItems method as shown in your example.

    For BroadcastReceiver, I have not tried this yet but I think this would be a great solution for decoupling receivers from activities. I have an ImageView that I set depending on result from a Service. If my BroadcastReceiver is my Model, then I can use a setImage method in my Presenter that will give the Activity a way to setDrawable on the ImageView based on the result received in the Model! Would this work?

  23. Thank @Antonio Leiva… i have a question… I use an Activity as View, has my Presenters.. and Model.. but i use a Service now with connection and binder in Activity. How can i use Service in MVP ? I could i use a Facade Pattern… with Context to create communication with Service and so send facade instance to my presenter ?

    1. Antonio Leiva

      Yeah, that’s what I’d do. The problem if you’re not using dependency injection is that you’ll need to pass the context throughout the layers.

  24. I am curious if you considered adding RxJava to this architecture? It provides all the benefits of AsyncTask and Handlers, but with many state-saving optimizations.

    1. Antonio Leiva

      Didn’t have time to get into RxJava yet, is one of my pending tasks. But it will probably work fine in this context, yeah.

  25. Hi Antonio,
    I wonder why you have all those interfaces and then implementing them,
    instead of just having concrete classes. What are the advantages?
    Thanks in advance.

    1. Antonio Leiva

      Ideally we should code against interfaces and not implementations so that they are easy to change, mock, test and keep layers well separated. In practice, you will need to find a balance and create interfaces for what you really need.

  26. Can you show how to implement this pattern in a rest Client with SQLite database persistance. I understand how you make the model and the view. However. you are losing me with the API call + SQLite CRUD in the presenter. For Example

    1. Hey Anton

      I was searching for how to decouple an app’s model layer from gui specifics, in this case, Android.

      I had a look at your example project at github and, no offense, but now I know that this is not the way I want to do it. You need no less than 5 java files for a login screen?

      There must be a simpler way to do it. I will have to see if this robobinding framework allows for something simpler, or maybe I can exploit groovy’s dynamic features, now that it officially supports android.

      Best, Luca

      1. Why not try Mosby MVP framework? It implements the LCE pattern, as well as RxJava and Dagger2. Overall, it is the latest and greatest in MVP land for Android.

  27. Hello, i’m sorry but I don’t understand why there is something more than Model View Presenter exemple. I’m talking about the interactor. Isn’t it a part of th presenter ?
    I also have a question, which pattern would you choose between MVC and MVP for an app using Bluetooth Low Energy to “interact” with a remote bluetooth device ?

  28. Hello everybody , I have a problem With This pattern , I must to save a preference on the device , but I do not know if put the call on the view or model . Any ideas?

  29. How should i process activity intent extras with this pattern? Because my presenter hold reference to some data, and my view(Activity) need to start another activity with their presenter data, should i call getter on presenter from the view or it’s bad practice?

    1. Lets say i’ve an CustomerActivity, which can add new customers or edit ones, this activity will find for customer parcelable in extras, if exists than populate the form data, if not leave blank, this activity can be initialized from many activities. The problem is: The activity which starts CustomerActivity for edition will need to send the extra to the intent, but the presenter is holding the reference, so i cant call startActivity without getting info from presenter, i’m felling bad with this, there’s another approach?

      1. The presenter can use a kind of Navigator, a class which holds a reference to the activity (this is easier if you use a dependency injector such as Dagger), and use it to navigate passing the information to this object.

  30. Davide Schembari

    Hi,

    I’m trying to implement a very simple version of MVP.
    I’ve got a conceptual issue right now which is: If the Presenter should be responsible to talk to the Model to retrieve data to feed the View layer with, and if Activities belong to the View layer, what happens when, for instance, a ListItemActivity launches a DetailItemActivity, where the item details are passed from the ListItemActivity to DetailItemActivity by means of a Bundle?
    I’m trying to find coherence in MVP and the monolithic architecture of Android.
    In the case I’m describing it seems the View layer (Activity) would need to pass data to the Presenter which may do some processing on them and pass such processed/formatted data back to the View layer (i.e. Fragment).
    To be honest I don’t agree much with considering Activities like dumb objects in the View layer, but that’s why I’m asking here 🙂

    Thank you.

    1. All these concepts work better with a dependency injector such as Dagger. You could inject a navigator to the presenter, which has the activity context injected too, so when an event triggers a navigation action, the presenter receives the action and calls the navigator directly. You conceptually don’t need to go back to the activity. Btw, regarding your feelings about activities not feeling like a dumb object, I’m nowadays studying other alternatives, such as using the Activity as a controller and Fragments as Views. In the end we are attached to the activity lifecycle, so every solution has its own pros and cons.

      1. Davide Schembari

        Thank you Antonio for your superquick reply.
        I’m trying not to depend on 3rd-party frameworks such as Dagger.
        I don’t have anything religious against it, I actually think it’s a great library, but for some projects, like the one I’m working on, it’s a bit too much.
        I’ll stay tuned to check other alternatives coming up.
        Thank you.

  31. Hi, thanks for the post. Im interested to know how you handle the case where a Presenter-backed Activity (lets call it X) is created and starts some work, a new Activity is pushed onto the stack and X is killed in the background, the presenter for X calls a load of the view methods (show something, change some text, start some animation etc), and then X comes back into view after having missed all the callbacks. As far as I can see using this pattern X and the presenter will be out of sync. I would be interested to know how you handle this case. Thx

    1. It depends on many things. You can just cancel the work you’re doing just before moving to the next activity, if that work only is only to fill the information of that activity. You can also persist the result of that work, which will presumably continue even though the activity is finished (this depends too on the architecture of the app). You essentially have the same issues you’d have when not using a presenter. If the activity was destroyed (this is the least probable case), you’ll need to recreate the view anyway, and any info you saved will need to be informed to the presenter. If it didn’t, everything will just work.

  32. I have an Activity with multiple Fragments. Should I implement all my Fragments with MVP as well? it seems a bit too much…..

    1. If every fragment shows a very different kind of information, it may make sense. But it depends on what you think is better.

  33. Davide Schembari

    I think after the introduction of Data Binding, there aren’t many reasons to go to a MVVM approach instead. Isn’t it the case?

    1. Davide Schembari

      I didn’t phrase this correctly 🙂 I meant that in my opinion there aren’t many reasons to go for MVP and I now prefer adopting MVVM instead as Data Binding provides us with a quite powerful framework, although still in beta.

  34. Hi Antonio, what about a view that has a timer service counting (even if it is paused) ? the activity starts the service and the presenter should listener for bus events? in that way there’s to way to test if that is working, then how can it be testable?

  35. Thank you for a great sample of code illustrating an android implementation of this concept. I watched a talk by Robert C. Martin on clean code which I really enjoyed but I couldn’t really imagine how it would be implemented. This made me understand it better.

    I just wonder, what is the point of using an interface for the interactor? I understand that if the interactor want to call methods on the presenter, then the presenter would have to implement some interface because of the needs of dependencies to point inwards toward the use cases. But why can’t the interactor just declare some methods public which then the presenter can call? Is it because some other class might want to use the interactor which might not use some of those public methods?

    Also, do you have some other projects using this concept? It would be interesting to see how you would deal with more interactors. Is this the foundation for most of your android projects?

    1. Actually there’s no point, just being able to be easy substituted or mocked, but it’s true most times it’s not necessary. I don’t bigger public repos, but it scales really well. I tend to use this architecture whenever I can, yeah, though I’ve been working in the same project for more than a year now, so I’d probably spend some time thinking about it before starting a new project. I recommend you to take a look to a couple of blogs: panavtec.me and pguardiola.com. They’re talking a lot about these topics recently.

  36. How would you go around the fact that the Presenter is stateful, and exposes a publicly accessible API? This could be dangerous, if the same Presenter instance ends up in the hands of the another component. I would prefer a way of indirect message passing from the View to the Presenter, in which it is clear and unambiguous that the View is the only one who could make calls to the Presenter. I would make all Presenter methods private, and rather make the View expose an event bus (many implementations available already) to the Presenter. When a View event happens, the View would rather send an event through the bus, which will be caught by the Presenter, verified if it’s the same view instance, and reacted upon.

    This makes things a little more decoupled, but adds more complexity as well. I would like to hear your thoughts on this.

    1. I’m not sure if this complexity really provides enough benefits. I prefer being more pragmatic and not to add so much complexity to be extra defensive. Have you found problems with this approach? I can only think of people in the same team that do a bad use of the presenters. But if the architecture is done properly, probably presenters are only accessible from views. I hadn’t heard about your idea before tbh, but looks like it would work too.

  37. Hi there, thanks for the thorough post. I am a bit late with on the mvp bandwagon but I am trying to catch up.
    You mentioned that you are using dagger together with mvp. How do you deal with the fact that the dependency between the presenter and the view is cyclical?
    I would like to inject stuff like the database helper and the rest client in my presenter but if I understood correctly I can’t since it cannot have a @Inject signed constructor because of that cyclical dependency

      1. The thing is you are not injecting fields in the PresenterImpl but passing them as constructor parameters instead of having a @Inject constructor and the fields injected.

        public MainPresenterImpl(MainView mainView, FindItemsInteractor findItemsInteractor) {

        and (I think) part of the reason is because you can’t inject the view in it while injecting the presenter in the view (the circular dependency I was talking about).

        So the view is passed to the module and then to the presenter itself “manually” because it is not partecipating to the dependency graph.

        What I missed (and makes your example super useful) is the fact that if I have a FindItemsInteractor as the argument of the provides method, it is resolved by the graph and I can replace it with a mock one in my tests.

        Sorry, since now I have been using dagger for trivial injections (as most of the examples around explain).

        Hope I was clear, your example was :-). Thanks again.

  38. This article was a very good start for MVP. However, I got stuck into this problem, where to put SharedPreferences? I have seen examples where Context is passed to the Presenter, but as you say, it should never go to the Presenter. Also, how to create Model if it is void of Context, AsyncTask, SharedPreferences or other Android specific classes. I couldn’t find any example of creating Model which would interact with database or the network. What is your approach on this, where to put Context, AsyncTask, SharedPreferences, etc.

  39. First of all , thanks a lot for a great tutorial. I am still finding it difficult to understand the overall picture. So far to construct MVP, one need to know the feature one is trying to implement. Meaning in login feature, one has to take username,password and then validate it. Then we need to identify which view plays part in this feature. The view then needs to define what interactions are possible for this view. Then the presenter identifies the core part of feature which is credential validation. The presenter then delegates the credential validation to the Interactor part. Is interactor part of presenter or part of model? Further in the example you have provided ,the validation is done on Interactor part. Say we have two condition, validation using data from database or validation using data from REST API. So , we need to define those portion on interactor part ?
    Thank you once again for awesome tutorial like this.

  40. Hi, is it a good idea when we have a complex view hierarchy to have similar hierarchy of contained presenters and communication via EventBus? What if one presenter is responsible only to handle a given chunk of the hierarchy and delegates to child presenters?

  41. Hi Antonio,

    Very good article that I enjoyed reading – MVP is something that makes so much sense, in terms of decoupling, and designating specific tasks/roles to each layer.

    I’ve been using this pattern, and have come to a stumbling block that I’d appreciate your thoughts. So far I’ve implemented a MVP pattern where Models haven’t needed to communicate with other models, however I’ve come to a situation where I need to do this. I know that I should do this through the Presenter layer. The problem is that I have 2 Views (Activity’s in this case), 2 Presenters and 2 Models – how do a say communicate to Model B, from Model A? Model A has a reference to Presenter A, and Model B has a reference to Presenter B, but not Model A to Presenter B, or Presenter A to Model B? Currently the View(Activity) initialises the Presenter which then initialses the Model for each Activity, I have no idea (to mind) where references can be passed between different Presenters. The type of structure I require is something like this : http://i.stack.imgur.com/Pa0iB.png – I’m guessing, as I haven’t used a Dependency Injection Library yet, that this is where it would be made possible by Injecting the Presenters, if each Presenter uses the @Singleton annotation, into each model to provide the references to them.

  42. Hi,

    I’ve implemented MVP pattern just like you mentioned. My earlier requirements were very simple. A simple GET request would give me data which Presenter used to pass on to View. For making network request I’ve used Volley.
    Now, network API’s have changed. For making a request, each request needs a token.
    For managing Token, I’ve create TokenManager API.
    Right now, I’m confused if token should be passed from View to Presenter and Presenter will pass the token to service API. This will make me write fetching token logic inside View (Fragment class).

    Or should I make Network API take care getting fresh token when needed.
    This will make ServiceAPI having 2 roles (getting actual data and manage token as well)

    Can you please suggest me a clean approach?

  43. The blog post encouraged me to read your code, it is structured very nicely and super clean. Going to bookmark.

  44. it is indeed a great blog. i want to exlopre more about mvp by going through some more code which involves background sync, services, broadcast receivers, view upading from service etc. can i get to see any project build on MVP. it would be great help for me. thanks!

  45. HI,Antonio,it’s an impressive article about MVP and MVP is new to me .So I wonder can I repost your article into Chinese on my blog? Of course I will indicate it comes from your blog.It will be great to recive your reply.

  46. I have 4 different fragment with different each having as below interfaces but my question is this that do I have to create different interfaces for each fragment as per MVP

    interface View {

    void getInvitesAndRequestsList();

    void setInvitesAndRequestsList(SOACompleteModel invitesList, InboxRequestResponseModel requestsList, int from, List miniProfileInvitesList);

    void setInvitesAndRequestsList(List miniProfileInvitesList, int limit, int scrollToPosition, boolean isDownloading, String calledFrom, String refineParams, String mKey, int from);

    void loadMore(int page, String key);

    }

    interface Listener {
    void getInvitesAndRequestsList(String refineParam, String key);

    void setInvitesAndRequestsList(SOACompleteModel invitesList, InboxRequestResponseModel requestsList, int from, List miniProfileInvitesList);

    void loadMore(int page, String key, String refineParam);

    void openProfile(int position, ArrayList minidataListExisting, int sourceSubType, String selectionTypeForInbox, int dbType);

    void setInvitesAndRequestsList(List miniProfileInvitesList, int limit, int scrollToPosition, boolean isDownloading, String calledFrom, String refineParams, String mKey, int from);

    void noResultRedirection();

    void setOnActivityResult(int requestCode, int resultCode, Intent data, InboxRequestResponseModel mInboxRequestResponseModel, int from);

    void getCallDetails(android.view.View v, int position, MiniProfileData miniProfileData);

    void clearApicallObjects();

    void clearDb(int dbType);

    }

    interface Interactor {

    void openProfile(int position, ArrayList minidataListExisting, int sourceSubType, String selectionTypeForInbox, int dbType);

    void getInvitationAndRequestList(int page, String refine, String key);

    void setOnActivityResult(int requestCode, int resultCode, Intent data, InboxRequestResponseModel mInboxRequestResponseModel, int from);

    void noResultRedirection();

    void getCallDetails(android.view.View v, int position, MiniProfileData miniProfileData);

    void cleanCallApiObjects();

    void clearDb(int dbType);

    }

  47. As you said, there are many implementations of MVP, but not all of them designate Activities and Fragments as views. I personally believe, that Activities and Fragments should not contain UI logic at all.
    My thoughts on the subject are described in this post: http://www.techyourchance.com/activities-android/
    Alternative implementation of MVP, where Activities and Fragments are presenters, is described here: http://www.techyourchance.com/mvp-mvc-android-1/

    1. What I mean in this article is that this is a way to model the UI, but the “Model” part of MVP will need an architecture too. Otherwise you’ll be only moving the problem to another part of the code. If it’s technically an architectural pattern or not is not that important.

  48. Hi, Antonio. I’m very new to Android and I’m trying to wrap my head around the MVP design pattern.

    I’ve been stuck on the subject of the role the Recyclerview adapters play in all this and how to implement it. Should I create a separate class for it (and its viewholder) and instantiate it inside the activity or fragment? Or is it better to create it as an inner class in the activity/fragment? How do I handle the data related operation that it needs? Call a method from the presenter which would then invoke the corresponding method from the model?

    If you have or can point me in the directions of a good, simple tutorial (preferably without the use of Dagger, as I feel it complicates things a bit for me), I would appreciate it greatly.

    Thanks in advance.

    1. Hey Adrián. I seldom use inner classes, but that’s a matter of taste I guess. Activities and adapters tend to grow fast, so better if they’re independent. The activity calls the presenter to update data, the presenter calls the model, and when it receives the data, calls the view (the activity in this case) which will update the data in the adapter. The adapter, for me, is part of the view, so the presenter doesn’t need to know of its existence. I’ll try to find some time to implement an example if it helps, but can’t promise anything

  49. Hi Antonio,
    Thanks for the detailed knowledge of MVP.
    Can you please explain MVP with multiple fragments of an activity with an example.

  50. Md Maidul Islam

    HI Thank you very much. I am learning MVP . I just try receive data from web-services. I go to your FindItemsInteractorImpl.class. I just implemented in CreateArraylist Methods. I write the code below.
    ArrayList beanBlocksIDs=new Arraylist();
    Call request = Network.getBaseInstance().getBlocksID();
    request.enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) {
    int statusCode = response.code();
    if (statusCode == 200) {

    beanBlocksIDs= response.body().getObject();

    } else {
    Log.e(TAG, “response code is ” + statusCode);

    }
    }
    @Override
    public void onFailure(Call call, Throwable t) {
    Log.e(TAG, “there was problem in response”,t);
    }
    return beanBlocksIDs;
    });

    Service is working fine.I check on debug. So My point is how can I return arraylist from here. Please let me know. I know your code working fine,Problem is mine. so please help me.

  51. Hi Thanks for your wonderful tutorial on mvp.Can you please add one post relating to webservices like volley using mvp pattern.Thanks in advance

  52. How do we implement RoboSpice in mvp architecture?? could you give me some tips or an overview?

  53. Hi Antonio,

    How we gonna handle the presenter when activity is recreated since presenter scope is coupled with activity lifecycle. The data might get lost which is saved in presenter object.

  54. Hi,
    Thats a great tutorial out there. The concept of interactor is taken from VIPER pattern am I right? If i m using viper pattern in my app is not it better to have the the login interactor implement the LoginInteractor.OnLoginFinishedListener so my api service can notify the interactor which in turns notifies the presenter and then to the view?

    1. The interactor concept is taken from the clean architecture that Uncle Bob raised some years ago. I’ve never used VIPER, so not sure if they’re the same. The thing is that interactors are normally used to move to a background thread, so that from that point all the domain logic can be synchronous. That’s not represented here because I just wanted to explain MVP and not to overcomplicate things.

  55. I wonder how some components fits in MVP. Many sites doesn’t explain this: how this fits with components like alarmmanager and a service. The former triggers timely and the another works in the background. Imagine a sync service that is called after 5 minutes to upload some data. Both components doesn’t handle data directly. Where these components fits in MVP? There are many others but for now I restrict with these two.

    1. It depends on what they are used for, but usually MVP needs to be used in a more complex architecture (clean architecture for example) and those components are part of the data layer. They tend to be just helpers that are wrapped by classes in your domain, so that you can isolate from the framework.

  56. Like most architectural patterns MVP is open to a lot of variety and experimentation and its implementation can be ambiguous. Lot of thanks for sharing this information.

  57. Sandeep Dheringe

    Hello,

    Thank you for such a helpful blog regarding MVP.
    I have some doubt while making some background call.

    I am designing a chatting application where I want call message sending API from UI when user sends message.
    I should also be able to send message in case of no internet. In such cases, i would require to call API for message send from background (May be service or broadcast receiver) when internet arrives and app is not running to retry all the pending messages.

    My question is where should i write the piece of code which is require to be executed from UI as well as background (where i do not need to update UI)?

    Apart from it further i would like to ask,

    Can my presenter and interactor be static?

    Thanks in advance.

  58. Rafael Ruiz Muñoz

    Hi Antonio!!
    I bought one of your e-book long time ago and I followed your MVP post for my last big project (in Kotlin though, I’m preparing a post for Medium that you might like).

    I had a concern:
    I really understand that you use an interface called LoginView, to be able to interact from the Presenter.
    But why does the presenter has an interface too? Could you bring any example of why that is useful?

    Un saludo!
    Rafael.

    1. It doesn’t indeed. I normally don’t use an interface for presenters. That’s one of the things I’ll change if I (once and for all) find time to update this article.

  59. Hi,
    I was wondering how to you MVP, assuming its a forward navigation. For eg going from List to Details where list passes all the data required to details. How do we separate the view and presenter in details

    1. If you’re passing it in the intent, you can extract the content in `onCreate` and call an `init()` method for the presenter that receives those items.

      1. Strictly in mvp view should be getting all the data through presenter and in this case view already have data which I wanted to avoid.. is there any better design pattern to tackle this sort of navigation where view strictly gets either static or dynamic data from presenters.

  60. Hi, thank you for this blog. What if we have to handle an onclick in the adapter, could you please let me knw the best way of doing it? Do we handle an activity change in the adapter when the onclick is performed or do we use listeners to send this event back to the presenter?

    1. What I do: the adapter notifies the activity with a listener, and the activity notifies the presenter with a method called “onItemClicked” or whatever, and the item clicked as the argument. What you pass to the presenter is the model of the item that was clicked, not views, or positions, or anything like that. Could be the id of the item if that’s all that you need.

  61. Hi, thanks for posting the example. In order to understand better the implementation of the MVP I would like to know why do you set to null the view variable in onDestroy method of the presenter. I mean in

    @Override public void onDestroy() {
    loginView = null;
    }

    It is certainly not hurting, but would like to know whether anything bad might happen if you don’t set it to null. Thank you.

    1. The reason is because if you’re doing a long running task and the task finishes after the activity has died, when the presenter tries to update the UI, it will crash. If you don’t have any asynchronous tasks that can lead to this situation, then you don’t need to clear the view.

  62. Looking at Github I find the code organized by activities (main, login).
    From the reference to Uncle Bob, I assumed to find it organized by entities, use cases, presenters and ui. I could not map the code at GitHub myself to this approach. Can you offer advice or am I missing something fundamental?

    My second problem is that I did not understand the use of interfaces and thier direction. From the dependency rule it seems that the inner rings should offer interfaces to the outer and not the outer to the inner. Reading other posts, e.g. https://fernandocejas.com/2014/09/03/architecting-android-the-clean-way/ it seems that this is not true as his domain layer has interfaces to the data layer and the presentation layer.

    Advice and help is appreciated.

    1. Yeah, this example doesn’t cover a complete clean architecture, only the presentation layer. That’s why you don’t find some of the layers. Understanding MVP is difficult by itself, let alone if you add the whole clean architecture.

      Regarding your second question (and this is something that took me quite some time to understand), the inner layer is the logic. The graph in that article is not accurate, because only takes into account a UI interaction, but not taking into account other interaction with external components. The data layer is an external layer, because it will require specific parts of the framework to interact, and those are implementation details.

      So the business logic is the inner circle, and it will use interfaces to communicate with the rest of layers: on the UI side you will probably have and interactors layer that will use the domain, and a presentation layer that will use the interactors. On the data side you will have a data layer (for instance with network and persistence) that will use the domain, and a framework layer (that could be an implementation using Retrofit and Room) that will use the data layer.

      There are a lot of articles about clean architecture, but I might write another one to explain it as simple as possible, because I think we can do a better job there.

  63. Thanks for the great tutorial. I do have one question. Suppose if I want to create a dynamic views in fragment based on a JSOn date. How will you separate the view and presenter? Will the dynamic creation logic will be in presenter or Fragment. Personally I would love to be in Fragment and I don’t want to pass view to presenter. What do you think, how this use case fits in MVP?

    1. You have two options: do the fragment a little more clever and leave that logic there, or have a method in the View interface that the presenter can use to do that action. But the View from the Android framework should never reach the presenter, nope.

  64. One confusion what I have is what to do when we are in the middle of a logic in presenter and we need to do something which requires reference to context. Is passing context to presenter’s default constructor a better idea or calling view’s method and getting return value in presenter is a better one.

    1. No, the presenter should receive an an object as a constructor that already has everything set. I wouldn’t allow the context to reach the presenter. This is all easier if you use dependency injection.

      1. And what do you think about passing the Context to single methods inside the presenter? I’m doing this to check localised strings, for example:

        class Presenter(view: MyViewInterface) {

        fun myMethod(context: Context): Boolean {
        return context.getString(R.string.localisedStore) == “US”
        }

        }

  65. Hi Antonio,

    First of all thank you for article.

    I’m trying to use MVP approach in my project.
    I have text field where user has to fill in birthday date using DatePicker dialog.
    User click on date field -> open date picker dialog -> user click set button in dialog -> date from dialog sets in date field.

    My question is:
    On your opinion, does presenter has to have methods like
    – onDateFieldClick() (then presenter call view.openDatePickerDialog() )
    – onDateDialogSet(Date date) then presenter call view.setDate(Date date)
    ?

    Currently I have this methods, but now I think that they are redundant because view can easy call method to open dialog, then dialog set data to field.

    Thank you.

    1. It depends. If you don’t need anything else, I think that those are view implementation details. If the presenter is view agnostic, you could have another interface that just shows a field for the date and doesn’t need to show a dialog. But if you, for instance, have to send those clicks to an analytics service, you will need to have them in the presenter. So both solutions are valid, with the exception that with the second one you may need to do a little refactoring in the future.

  66. I understand the MVP. However i do not understand model belongs to presentation layer or domain layer. you say that model is in presentation layer. however in many of other resources, for example, in other resources https://proandroiddev.com/clean-architecture-data-flow-dependency-rule-615ffdd79e29 , model belongs to domain layer as shown in the figure. Which one is correct? Thanks in advance. Model does business logic. domain layer does business logic too. Thus, logically it should be belong to domain layer.

    1. Here I’m only explaining the presentation pattern, not a complete architecture. As I mention in the model section, the “Model” of Model View Presenter would just be the gateway to the rest of the layers. But talking in a more general way, a strict clean architecture would have a model per layer, and there is a model conversion when you move from one layer to the next one. I have another article about clean architecture that may clear out your questions: https://antonioleiva.com/coroutines/

  67. From your code i can see that your view is giving instructions to your presenter to validate the data like
    private fun validateCredentials() {
    presenter.validateCredentials(username.text.toString(), password.text.toString())
    }

    But in opinion your presenter should decide what to do.
    Like presenter.onLoginButtonClicked(username.text.toString(), password.text.toString())

    and in your method onLoginButtonClicked() implementation it should be decide whether you want to validate the data or your want to process the data to rest api.
    Hope you got the difference.

    1. Yeah, totally agree with you. That’s something I’ve changed since I wrote this article, but never remember to update it. But that’s how it should be. The view only informs about what is happening, but should never decide what the presenter should do.

  68. should view be calling presenter methods or is it okay if the presenter sets listeners and implement the logic inside the presenter itself?

    1. That’s also an option too. I’ve never seen it with the presenter itself, but when people use Jetpack ViewModels and LiveData without data binding, that’s exactly what you mentioned.

  69. Simply setting your view to null and safe-calling your view methods may be a way to avoid crashes and leaks but what about user experience?! Let’s say a process is started and whose delivery time is about 10 seconds but after 5seconds user just clicks the home button and sends the activity to background what happens to results from your listeners? They won’t trigger anything in view and the result will just disappear without notifying the user of the changes. So, basically this write-up is just a very basic demo rather than a solution

    1. This article is to teach MVP from scratch, so explaining all the edge cases would be too much. Especially because each App has different ones. If the user clicks home, the Activity is not immediately destroyed, so it can still be updated. If it’s finally destroyed, then the request would need to be done again. That can be a perfect compromise solution for many Apps, as this is an edge case and the user normally only logs in once in an App, and they’re usually waiting for the App to finish login, not moving between apps.

Comments are closed.