Tag: presenter

Why use the MVP pattern?

One of the problems with traditional Android development is the tight coupling between Activities and business logic. This tends to make testing, extensibility and maintenance rather difficult.

The main idea behind using MVP is to take abstract away most (or all) of the business logic into separate entities (presenters) and only keep the UI logic in Activities.

There are many different types of MVP implementations for Android out there, this article only focuses on the basic principles behind them.

Presenter:

The presenter is a separate class that contains the business logic and a reference to its associated view.

The view itself is abstracted away through an interface. This is implemented mainly to allow the view to be mocked in a unit test or replaced with any other view that implements this particular interface.

An example of a basic Presenter.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

publicclassPresenter{

//The associated view

MainView mainView;

publicPresenter(MainView mainView){

this.mainView=mainView;

}

/**

* Some business logic

*/

publicvoidgetSomeResult(){

//call a method from the view

mainView.showToast("Here's your result!");

}

}

View:

The view is defined as an Interface which can be implemented by any Activity, Fragment or any type of Android View. This view contains methods that handle all UI logic.

An Interface containing View operations

1

2

3

4

5

6

7

8

publicinterfaceMainView{

voidshowLoading(booleanloading);

voiddisplayResult(Stringresult);

voidshowToast(Stringmessage);

}

Finally

The last step is to link everything together: a new Activity is created which holds a reference to the presenter and implements the View Interface.