Mobile App Deveploment

Mastering Android Architecture: A Tutorial on MVP or MVVM

Unlock the secrets of Android architecture with our tutorial on MVP or MVVM! Dive deep into mastery at Shiv Technolabs.

This post is about Android architectures to make testability better. Read on to know the complete details.

1. Architectures for Android


Architectures for Android

In default templates, they make you create large activities or fragments. These components usually have business logic mixed with their UI logic. Because of this, it becomes difficult to test and therefore maintain Android applications.

There are several patterns which are popularly used in the Android community to make testing easier.

The most commonly used architectural styles include:

  • Model View Presenter (MVP)
  • Model View View Model (MVVM) with Android Data Binding

2. Android’s Model View Presenter Architecture


Android’s Model View Presenter ArchitectureThe Model View Presenter (MVP) architecture pattern improves the application’s architecture to make it more testable. The MVP pattern separates the data model from a view through a presenter.

2.1 A Visual Part

A view in MVP is a visual part of an application. It contains only the UI and doesn’t have any logic or knowledge about what data it shows. In most cases, a view in MVP (model-view-presenter pattern) exports an interface that is utilized by the Presenter – therefore, these methods are used by him to manipulate the view itself; for example: showProgressBar(), updateData() etc.

2.2 The Program Giver

The presenter triggers business logic and tells the view when to update; it interacts with the model hence fetching and transforming data from the model into updating views. If possible, a presenter should not depend on Android SDK.

2.3 Data Supplier

A model consists of two parts: a data provider and code that fetches/updates data. This section of MVP updates databases or communicates with web servers.

2.4. Things to Consider When Using the Design Pattern MVP

MVP makes it easier for you to test your presenter logic and replace dependencies. But also with this comes longer application code. This structure may not be easily comprehensible by every Android developer as this is not followed in the standard Android templates at the moment.

2.5 Comparison to Model View Controller

In the Model View Presenter pattern, the views more separated from the model. The presenter communicates between model and view; this makes it easier to create unit tests Generally there is a one-to-one mapping between view and Presenter but also it’s possible to use multiple presenters for complex views.

Also Read:- What are Widgets in Flutter? Exploring Types and Benefits

In Model View Controller pattern controllers are behavior based and can share multiple views. View can communicate directly with model. MVP is currently on of the patterns that the Android community prefers.

3. The Model View View Model Architecture for Android


The Model View View Model Architecture for Android

Also known as the Model View Binder, the design pattern Model View ViewModel.

3.1. The Scene

In MVP, a view component represents the visual part of an app.

Views are usually bound to observable variables and actions that are exposed by the view model via a data binding framework.

Some of the responsibilities of a view include:

  • Menus
  • Permissions
  • Event listeners
  • Showing dialogs, Toasts, Snackbars
  • Starting activities
  • All functionality related to the Android Context

3.2. Sight Model (ViewModel)

This is where we store all data that should be displayed in our application’s views. It acts as an intermediary between them – exposing public properties and commands, using observables so they can easily notify about any changes etc., also allowing events passing through it from models (a raw model data value converter into presentation friendly properties).

Below are the responsibilities of a view model:

  • Data Exposure
  • State Exposure (progress, offline, empty, error etc)
  • Visibility Handling
  • Input Validation
  • Executes calls to the Model
  • Executes methods in the view

The Application Context should be only known by the View Model. The application context can do things like:

    • Start a Service.
    • Bind to a Service.
    • Send a Broadcast.
    • Register a Broadcast Receiver.
  • Load Resource Values.

But it cannot do things like:

  • Show a Dialog.
  • Inflating a Layout.

3.3 The Model:

It contains the code to fetch and update data along with data provider. Different sources for getting data can be used such as:

3.4. Differences From MVP

This has a greater number of synonyms and uses them well. MVVM is more event-driven because it uses data binding. The presenter and the view are typically mapped one to one in MVP, but many views can be associated with a single view model in MVVM On this level, the view knows the presenter while in that level of abstraction the view model doesn’t have any reference to it.

Also Read:- How to Select the Right IoT Database Architecture?

4. Using Build Flavors as Architectural Style to Improve Testability


Using Build Flavors as Architectural Style to Improve Testability

Using build flavors can be done by developers for improving testability in their applications. They need to define different classes for providing data within each build flavor.

Here’s an example: if you had two flavors ‘prod’ and ‘mock’ then you could have these different implementations in your flavors.

This might be a theoretical implementation for the ‘mock’ flavor:

This could be a theoretical implementation for the ‘prod’ flavour.

In the case of your application code, you can access the provided implementation via Injection.provideNotesRepository(). You will receive the mocked version or the real one depending on which flavor you are building. Your unit test would build against the mock flavor to mock away external dependencies.

5. Enhancing Testability Using Dependency Injection as Architectural Style


Enhancing Testability Using Dependency Injection as Architectural Style

Dependency injection is a way of building testable applications. Most Android applications use Dagger 2 for dependency injection. When tests are run, they inject mock or fake objects. When the real application starts, correct objects are injected.

6. Presenter Testing


Presenter Testing

The presenter typically has dependencies, eg to an implementation of the view contract. To unit test the presenter, you mock or fake these dependencies away.

For example, testing the presenter we don’t need to know whether the view displays a dialog or progress indicator; but we want to test that presenter calls a method on view to display progress information.

7. Exercise Model View Presenter


Exercise Model View Presenter

Here you will design a small application for maintaining tasks. === Create a new application.

7.1 Generate Package

This project groups classes according to their use cases. Create these Java packages:

  • Createtask
  • Data
  • Overview
  • Util

7.2 Build Tasks Activity

Create a new TasksActivity and make it the entry point of your app.

You have a screen with an overview of repositories for the selected user. When you click on the repository, you would see details about this repository.

The contract between this view and presenter should be through a GitHubContract interface. The view would call one of its methods whenever it needs to perform an operation on the presenter, and when the presenter finishes, it would call back the view via defined interface methods.

In the create method of the activity you would instantiate the responsible presenter and pass a reference to the presenter to the view.

For the refresh action, put in at least a button. In the onClick method of the button, call loadRepositories on your presenter. Call setProgressIndicator method on the view in the presenter, create some test data and call showRepositories repositories on the view with this data.

Can you write unit tests for the presenter which could run on the JVM? Contact Shiv Technolabs now.

background-line

Revolutionize Your Digital Presence with Our Mobile & Web Development Service. Trusted Expertise, Innovation, and Success Guaranteed.

Written by

Kishan Mehta

I am a dynamic and visionary Managing Director of Shiv Technolabs, a leading IT company at the forefront of innovation. With over a decade of hands-on experience in mobile app development, web development, and eCommerce solutions, I am a qualified professional. My expertise goes beyond technical proficiency, containing a keen understanding of evolving market dynamics. I have successfully delivered exceptional IT solutions, catering to the unique needs of entrepreneurs and businesses across diverse industries.