Android

MVP Architecture Pattern in Android with Basic Example

Pinterest LinkedIn Tumblr

In the initial stages of Android development, Android learners do write codes in the Activity Java class which contains all the implementation of models, views, and controllers. It causes difficulties in the maintenance, scaling, or addition of the new features.

To avoid such problems in maintainability, readability, scalability, and refactoring of applications, developers prefer to define well-separated layers of code.
In Android, we have many architecture design patterns. We are going to learn MVP( Model View Presenter) which is one of the most popular architecture patterns and is valid in organizing the project.

1- Model holds the date of the application, It cannot directly talk to the view. It’s recommended to expose the data to the view by Interface.
2View represents the UI of the layout. After getting the data from the model, the presenter tells the View.
3Presenter is the bridge between model and view.

Jump to section

Demo

MVP Example Demo

If you already have a solid understanding RecyclerView and Data Binding, carry on. Otherwise, consider starting with Data Binding and RecyclerView tutorial first.

Step-1 (Create a new project)

Open the Android Studio, and create a new project, and select the blank template.

Step-2 (Add dependecies)

1- Go to the build.gradle.xml and add the below code and sync the project.

    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

2- Enable the data binding feature and sync again the Gradle

 buildFeatures {
        dataBinding true
    }

Step-3 (Project Resources)

1- Go to the strings.xml file and add the below code

<resources>
    <string name="app_name">MVP Example</string>

    <!-- App strings -->
    <string name="tv_username">John</string>
    <string name="tv_user_address">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque quis elementum nisi. Vivamus neque leo, eleifend ut tempus elementum, dictum eget massa</string>

</resources>

2- Go to the colors.xml file and add the below code

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>

    <!-- app colors -->
    <color name="color_bg">#121212</color>
    <color name="color_tv">#00FFFF</color>
    <color name="color_dark_black">#1D1D1D</color>

</resources>

Step-4 (Design a layout for RecyclerView row)

Create a new layout resource file and renamed it with adapter_listing.xml. Add the below code to it.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardListing"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="5dp"
        android:minHeight="140dp"
        app:cardBackgroundColor="@color/color_dark_black"
        app:cardCornerRadius="5dp"
        app:cardMaxElevation="5dp"
        app:cardUseCompatPadding="true">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_margin="5dp"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/tvUsername"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_constraintEnd_toEndOf="parent"
                android:text="@string/tv_username"
                android:textColor="@color/color_tv"
                android:textSize="20sp"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/tvUserAddress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/tv_user_address"
                android:textColor="@color/white"
                android:textSize="16sp"
                app:layout_constraintStart_toStartOf="parent"
                android:gravity="center"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/tvUsername" />

        </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.cardview.widget.CardView>
</layout>

Step-5 (Create a Model class)

Create a new Java class and renamed it with ListingM.java. Add the below code

package com.example.mvpexample;

public class ListingM {
    private String name;
    private String address;

    public ListingM(String name, String address) {
        this.name = name;
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

Step-6 (Create a View Holder Presenter for Adapter)

Create a new class named ListingViewHolderPresenter.java to separate binding reference and business logic. This class will get the value from View Holder and will set it to the views. Add the below code

package com.example.mvpexample;

import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mvpexample.databinding.AdapterListingBinding;

public class ListingViewHolderPresenter extends RecyclerView.ViewHolder{
    private AdapterListingBinding adapterListingBinding;

    public ListingViewHolderPresenter(@NonNull AdapterListingBinding adapterListingBinding) {
        super(adapterListingBinding.getRoot());
        this.adapterListingBinding = adapterListingBinding;
    }

    public void setUpValues(ListingM listingM) {
        adapterListingBinding.tvUsername.setText(listingM.getName());
        adapterListingBinding.tvUserAddress.setText(listingM.getAddress());
    }
}

Step-7 (Create RecyclerView Adapter class)

Create a new Java class and renamed it with AdapterListing.java. If you’re following my tutorials, then I have already written tutorials on DataBinding and RecyclerViews. Add the below code

package com.example.mvpexample;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class AdapterListing extends RecyclerView.Adapter<ListingViewHolderPresenter> {
    private List<ListingM> listingMList;

    AdapterListing(List<ListingM> listingMList) {
        this.listingMList = listingMList;
    }

    @NonNull
    @Override
    public ListingViewHolderPresenter onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ListingViewHolderPresenter(DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.adapter_listing, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ListingViewHolderPresenter holder, int position) {
        holder.setUpValues(listingMList.get(position));
    }

    @Override
    public int getItemCount() {
        return listingMList.size();
    }
}

Step-8 (activity_main.xml)

Open the activity_main.xml file and add a TextView and RecyclerView to display the demo title and listing. Below is the code for designing a proper activity layout using constraint layout and constraint helpers.

<?xml version="1.0" encoding="utf-8"?>
<layout>

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/color_bg"
        tools:context=".MainActivity">

        <TextView
            android:id="@+id/tvHeading"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name"
            android:layout_marginTop="20dp"
            android:textColor="@color/color_tv"
            android:textSize="24sp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rcvListing"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            android:layout_marginTop="10dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tvHeading"
            android:layout_width="0dp"
            android:layout_height="0dp"/>

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

Step-9 (Creating the Activity Main Presenter class)

Create a new Java class and named MainActivityPresenter.java. This class contains core business logic that will prepare the dummy data, initialize the UI, and set the data to the listing. Add the below code

package com.example.mvpexample;

import android.content.Context;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mvpexample.databinding.ActivityMainBinding;

import java.util.ArrayList;
import java.util.List;

public class MainActivityPresenter {
    private ActivityMainBinding activityMainBinding;
    private Context _context;

    /**
     *
     * @param activityMainBinding binding class of the MainActivity
     * @param _context current activity reference
     */
    public MainActivityPresenter(ActivityMainBinding activityMainBinding, Context _context) {
        this.activityMainBinding = activityMainBinding;
        this._context = _context;
    }

    /**
     * prepare the dummy data for listing and set this data to adapter for displaying dummy information of user.
     * you can change accordingly your logic
     */
    public void prepareDummyDataForListing() {
        List<ListingM> listingMList = new ArrayList<>();
        for (int j = 0; j < 10; j++) {
            listingMList.add(new ListingM(_context.getString(R.string.tv_username), _context.getString(R.string.tv_user_address)));
        }
        AdapterListing adapterListing = new AdapterListing(listingMList);
        activityMainBinding.rcvListing.setAdapter(adapterListing);
    }
    public void initRcv(){
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(_context);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        activityMainBinding.rcvListing.setLayoutManager(linearLayoutManager);

    }
}

Step-10 (MainActivity.java)

Go to the MainActivity.java file and add the below code.

package com.example.mvpexample;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

import com.example.mvpexample.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    private MainActivityPresenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        presenter = new MainActivityPresenter(binding, this);
        presenter.initRcv();
        presenter.prepareDummyDataForListing();
    }
}

Step-11 (Download Android Resources)

//download the code

Thanks for reading the tutorial. Subscribe to my YouTube channel. Like and Share my Facebook page with your friends.

Write A Comment