Android MVP Architecture

MVP (Model-View-Presenter) is one of well know design architecture for android application development.

Why need MVP

MVP separate the application UI logic from the business logic. At the beginning of Android development, we write most of our codes in activity Classes. But when the application group it will hard to maintain the codebase. Also it hard to test each functionality individually because most of the functionalities are tightly couple with the activity class itself.

As an example let’s think we have an application to save our todo list to the local database and retrieve from the local database. Then later we need to change the data retrieve layer to get data from API. If we write this data get functionality inside the activity itself, we need to change a lot of codebase inside the activity if we change the data retrieving code. But if we write that using MVP architecture we don’t need to change the UI layer. We need to change only the data retrieve layer.

Components in MVP

In MVP are 3 main components.

Model – Model contain business logic and provide data to show in view. It include API call, database handle etc.

View – Has a reference to the activity. We call the interface methods when we need to trigger actions.

Presenter – This act as a glue between the Model and the View. Presenter view format the data to show in the view. Presenter contains a reference to the view and we call the interface method inside presenter.

Implementation

In this article, I’m gone a show you a basic example. In here user will be able to enter username and password and we validate the username and password and show whether the password and username are correct or not.

First, we need to create an interface to act as a View. In here I am gone add two methods to show valid and Invalid login.

public interface LoginMVPView {
    void showUserValidMessage();
    void showUserInvalidMessage();
}

Then create a presenter to make the connection between model and view. When we are creating an instance of presenter class inside activity, we need to pass the reference of view to the presenter.

public class LoginPresenter {

    private LoginMVPView loginView;

    public LoginPresenter(LoginMVPView loginMVPView){
        loginView = loginMVPView;
    }

    public void validateUser(String userName,String password){
        if(Validator.isUserValid(userName,password)){
            loginView.showUserValidMessage();
        } else {
            loginView.showUserInvalidMessage();
        }
    }
}

Inside the activity, you can create an instance of the presenter and when you press the login button It trigger the validateUser method inside the presenter.

Inside the validator class, You can add any validation logic. In here I’m only adding simple check with existing username and password. This can consider as a Model in MVP.

public class Validator {

    public static boolean isUserValid(String userName,String password){
        if(userName.equals("user1") && password.equals("pass@123"))
            return true;

        return false;
    }
}

This is the activity class which I call validateUser method and implement LoginMVPView.

public class LogInActivity extends AppCompatActivity implements LoginMVPView {
    LoginPresenter mLoginPresenter;
    EditText editTxtUsername,editTxtPassword;
    Button btnLogIn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLoginPresenter = new LoginPresenter(this);
        editTxtUsername = findViewById(R.id.editTxtUsername);
        editTxtPassword = findViewById(R.id.editTxtPassword);
        btnLogIn = findViewById(R.id.btnLogIn);

        //login click listner
        btnLogIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLoginPresenter.validateUser(editTxtUsername.getText().toString(),editTxtPassword.getText().toString());
            }
        });
    }

    @Override
    public void showUserValidMessage() {
        Toast.makeText(this,"User Valid",Toast.LENGTH_SHORT);
    }

    @Override
    public void showUserInvalidMessage() {
        Toast.makeText(this,"User InValid",Toast.LENGTH_SHORT);
    }
}

If you need a help to create a UI, you can use this layout.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
    tools:context=".LogInActivity">

    <EditText
        android:id="@+id/editTxtUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="284dp"
        android:hint="UserName"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editTxtPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:hint="Password"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTxtUsername" />

    <Button
        android:id="@+id/btnLogIn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="LOG IN"
        android:background="@color/colorPrimary"
        app:layout_constraintTop_toBottomOf="@+id/editTxtPassword" />

</android.support.constraint.ConstraintLayout>

Leave a Reply