Most of the guys heard about MVC(Model – View – Controller) architecture. So what’s new in this and how it helps me in Android?
First of all, MVP(Model – View – Presenter) is derived from MVC architecture. Here you can see, only one thing is different and it is a Presenter. In normal java programs controller handles the logic of controlling the views but in Presenter, we can do this kind of stuff
- Database operations
- Network activities
- Business logic
Model: Anything that contains data or digital resource, we called it as Model. It can be kind of data repository or network resource.
View: A group of elements or any visible thing that user can interact with, that is View. Specific for Android, it can be any activity, fragment or dialog
Presenter: Any part that can handles business logic or process intensive task, that called Presenter
Let’s understand MVP with the following example
Suppose, there’s a task that you need to call your own backend API and parse the results from the response and set the result to TextView. So here’re the steps you need to follow.
I assume that you have a basic knowledge of Android app development. So just focus on how you can implement MVP
- Under your package create two files named MainContract.java and MainPresenter.java. Now I know you get a question, What is this contract?
– A contract is an interface with two subinterfaces containing method description of both view and presenter.
- In MainPresenter create the constructor with an argument of MainContract.View and assign it to globally
- Implement interface as shown in below code. Like MainContract.View in MainActivity and MainContract.Presenter in MainPresenter. Doing this implements all method in the respective class.
- Create and initialize a MainPresenter object in MainActivity and call presenter method whenever you need
- in MainPresenter class, call MainContract.View’s method wherever you need.
- Your basic MVP app is ready
Please refer this code for better understanding
I hope above guide helps you to walk through about MVP architecture