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

  1. Database operations
  2. Network activities
  3. Business logic

Definition

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

  1. 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.
  2. In MainPresenter create the constructor with an argument of MainContract.View and assign it to globally
  3. 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.
  4. Create and initialize a MainPresenter object in MainActivity and call presenter method whenever you need
  5. in MainPresenter class, call MainContract.View’s method wherever you need.
  6. 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


Leave a Reply

Related Posts

Android

Get started with Notification Channels for Android Oreo

As the Android user and developer, this is one of the most features that I like in Android Oreo release. Now let’s discuss, what’s the Notification channels? Notification Channels is the feature that enables developers Read more…