Home » Java » MVC pattern on Android

MVC pattern on Android

Posted by: admin November 2, 2017 Leave a comment

Questions:

Is it possible to implement the model–view–controller pattern in Java for Android?

Or is it already implemented through Activities? Or is there a better way to implement the MVC pattern for Android?

Answers:

In Android you don’t have MVC, but you have the following:

  • You define your user interface in various XML files by resolution, hardware, etc.
  • You define your resources in various XML files by locale, etc.
  • You extend clases like ListActivity, TabActivity and make use of the XML file by inflaters.
  • You can create as many classes as you wish for your business logic.
  • A lot of Utils have been already written for you – DatabaseUtils, Html.
Questions:
Answers:

There is no universally unique MVC pattern. MVC is a concept rather than a solid programming framework. You can implement your own MVC on any platform. As long as you stick to the following basic idea, you are implementing MVC:

  • Model: What to render
  • View: How to render
  • Controller: Events, user input

Also think about it this way: When you program your model, the model should not need to worry about the rendering (or platform specific code). The model would say to the view, I don’t care if your rendering is Android or iOS or Windows Phone, this is what I need you to render.
The view would only handle the platform-specific rendering code.

This is particularly useful when you use Mono to share the model in order to develop cross-platform applications.

Questions:
Answers:

The actions, views and activities on Android are the baked-in way of working with the Android UI and are an implementation of the model–view–viewmodel (MVVM) pattern, which is structurally similar (in the same family as) model–view–controller.

To the best of my knowledge, there is no way to break out of this model. It can probably be done, but you would likely lose all the benefit that the existing model has and have to rewrite your own UI layer to make it work.

Questions:
Answers:

After some searching, the most reasonable answer is the following:

MVC is already implemented in Android as:

  1. View = layout, resources and built-in classes like Button derived from android.view.View.
  2. Controller = Activity
  3. Model = the classes that implement the application logic

(This by the way implies no application domain logic in the activity.)

The most reasonable thing for a small developer is to follow this pattern and not to try to do what Google decided not to do.

PS Note that Activity is sometimes restarted, so it’s no place for model data (the easiest way to cause a restart is to omit android:configChanges="keyboardHidden|orientation" from the XML and turn your device).

EDIT

We may be talking about MVC, but it will be so to say FMVC, Framework–Model–View–Controller. The Framework (the Android OS) imposes its idea of component life cycle and related events, and in practice the Controller (Activity/Service/BroadcastReceiver) is first of all responsible for coping with these Framework-imposed events (such as onCreate()). Should user input be processed separately? Even if it should, you cannot separate it, user input events also come from Android.

Anyway, the less code that is not Android-specific you put into your Activity/Service/BroadcastReceiver, the better.

Questions:
Answers:

There is no single MVC pattern you could obey to. MVC just states more or less that you should not mingle data and view, so that e.g. views are responsible for holding data or classes which are processing data are directly affecting the view.

But nevertheless, the way Android deals with classes and resources, you’re sometimes even forced to follow the MVC pattern. More complicated in my opinion are the activities which are responsible sometimes for the view, but nevertheless act as an controller in the same time.

If you define your views and layouts in the XML files, load your resources from the res folder, and if you avoid more or less to mingle these things in your code, then you’re anyway following an MVC pattern.

Questions:
Answers:

The best resource I found to implement MVC on Android is this post:

I followed the same design for one of my projects, and it worked great. I am a beginner on Android, so I can’t say that this is the best solution.

I made one modification: I instantiated the model and the controller for each activity in the application class so that these are not recreated when the landscape-portrait mode changes.

Questions:
Answers:

I agree with JDPeckham, and I believe that XML alone is not sufficient to implement the UI part of an application.

However, if you consider the Activity as part of the view then implementing MVC is quite straightforward. You can override Application (as returned by getApplication() in Activity) and it’s here that you can create a controller that survives for the lifetime of your application.

(Alternatively you can use the singleton pattern as suggested by the Application documentation)

Questions:
Answers:

Android UI creation using layouts, resources, activities and intents is an implementation of the MVC pattern. Please see the following link for more on this – http://www.cs.otago.ac.nz/cosc346/labs/COSC346-lab2.2up.pdf

mirror for the pdf

Questions:
Answers:

You can implement MVC in Android, but it is not “natively supported” and takes some effort.

That said, I personally tend towards MVP as a much cleaner architectural pattern for Android development. And by saying MVP I mean this:

enter image description here

I have also posted a more detailed answer here.

After playing with the various approaches to MVC/MVP implementation in Android, I came up with a reasonable architectural pattern, which I described in a this post: MVP and MVC Architectural Patterns in Android.

Questions:
Answers:

Although this post seems to be old, I’d like to add the following two to inform about the recent development in this area for Android:

android-binding – Providing a framework that enabes the binding of android view widgets to data model. It helps to implement MVC or MVVM patterns in android applications.

roboguice – RoboGuice takes the guesswork out of development. Inject your View, Resource, System Service, or any other object, and let RoboGuice take care of the details.

Questions:
Answers:

MVC- Architecture on Android
Its Better to Follow Any MVP instead MVC in android. But still according to the answer to the question this can be solution

Enter image description here

Description and Guidelines

     Controller -
        Activity can play the role.
        Use an application class to write the
        global methods and define, and avoid
        static variables in the controller label
    Model -
        Entity like - user, Product, and Customer class.
    View -
        XML layout files.
    ViewModel -
        Class with like CartItem and owner
        models with multiple class properties
    Service -
        DataService- All the tables which have logic
        to get the data to bind the models - UserTable,
        CustomerTable
        NetworkService - Service logic binds the
        logic with network call - Login Service
Helpers -
        StringHelper, ValidationHelper static
        methods for helping format and validation code.
SharedView - fragmets or shared views from the code
        can be separated here

AppConstant -
        Use the Values folder XML files
        for constant app level

NOTE 1:

Now here is the piece of magic you can do. Once you have classified the piece of code, write a base interface class like, IEntity and IService. Declare common methods. Now create the abstract class BaseService and declare your own set of methods and have separation of code.

NOTE 2: If your activity is presenting multiple models then rather than writing the code/logic in activity, it is better to divide the views in fragments. Then it’s better. So in the future if any more model is needed to show up in the view, add one more fragment.

NOTE 3: Separation of code is very important. Every component in the architecture should be independent not having dependent logic. If by chance if you have something dependent logic, then write a mapping logic class in between. This will help you in the future.

Questions:
Answers:

Android’s MVC pattern is (kind-of) implemented with their Adapter classes. They replace a controller with an “adapter.” The description for the adapter states:

An Adapter object acts as a bridge between an AdapterView and the
underlying data for that view.

I’m just looking into this for an Android application that reads from a database, so I don’t know how well it works yet. However, it seems a little like Qt’s Model-View-Delegate architecture, which they claim is a step up from a traditional MVC pattern. At least on the PC, Qt’s pattern works fairly well.

Questions:
Answers:

Model View Controller (MVC)

enter image description here


Description:

  • When we have to main large projects in the software development, MVC
    is generally used because it’s a universal way of organizing the
    projects.
  • New developers can quickly adapt to the project
  • Helps in development of big projects and cross platform too.

The MVC pattern is essentially this:

  • Model: What to display. This can be the data source (Ex: Server, Raw
    data in the app)
  • View: How it’s displayed. This can be the xml. It is thus acting as a
    presentation filter. A view is attached to its model (or model part)
    and gets the data necessary for the presentation.
  • Controller: Handling events like user input. This be the activity

Important feature of MVC: We can modify Either the Model or View or Controller still not affecting the other ones

  • Say we change the color in the view, size of the view or the position
    of the view. By doing so it won’t affect the model or the controller
  • Say we change the model (instead of data fetched from the server
    fetch data from assets ) still it won’t affect the view and
    controller
  • Say we change the Controller(Logic in the activity) it won’t affect
    the model and the view
Questions:
Answers:

I think the most useful simplified explanation is here:
http://www.cs.otago.ac.nz/cosc346/labs/COSC346-lab2.2up.pdf

From everything else I’ve seen and read here, implementing all these things makes it harder and does not fit in well with other parts of android.

Having an activity implement other listeners is already the standard Android way. The most harmless way would be to add the Java Observer like the slides describe and group the onClick and other types of actions into functions that are still in the Activity.

The Android way is that the Activity does both. Fighting it doesn’t really make extending or doing future coding any easier.

I agree with the 2nd post. It’s sort of already implemented, just not the way people are used to. Whether or not it’s in the same file or not, there is separation already. There is no need to create extra separation to make it fit other languages and OSes.

Questions:
Answers:

Being tired of the MVx disaster on Android I’ve recently made a tiny library that provides unidirectional data flow and is similar to the concept of MVC: https://github.com/zserge/anvil

Basically, you have a component (activity, fragment, and viewgroup). Inside you define the structure and style of the view layer. Also you define how data should be bound to the views. Finally, you can bind listeners in the same place.

Then, once your data is changed – the global “render()” method will be called, and your views will be smartly updated with the most recent data.

Here’s an example of the component having everything inside for code compactness (of course Model and Controller can be easily separated). Here “count” is a model, view() method is a view, and “v -> count++” is a controller which listens to the button clicks and updates the model.

public MyView extends RenderableView {
  public MyView(Context c) {
      super(c);
  }

  private int count = 0;

  public void view() {
    frameLayout(() -> {              // Define your view hierarchy
      size(FILL, WRAP);
      button(() -> {
          textColor(Color.RED);      // Define view style
          text("Clicked " + count);  // Bind data
          onClick(v -> count++);     // Bind listeners
      });
    });
  }

With the separated model and controller it would look like:

button(() -> {
   textColor(Color.RED);
   text("Clicked " + mModel.getClickCount());
   onClick(mController::onButtonClicked);
});

Here on each button click the number will be increased, then “render()” will be called, and button text will be updated.

The syntax becomes more pleasant if you use Kotlin: http://zserge.com/blog/anvil-kotlin.html. Also, there is alternative syntax for Java without lambdas.

The library itself is very lightweight, has no dependencies, uses no reflection, etc.

(Disclaimer: I’m the author of this library)

Questions:
Answers:

I have seen that many people are saying MVC is already implemented in Android, but it’s not true. Android follows no MVC by default.

Because Google don’t like to forcefully impose the restrictions of an MVC implementation like iPhone, but they have left this decision on the user to use the MVC technique, because in small or simple applications we have no need to use MVC, but as the application get complicated and will have need to modify its code after the development completes, then there comes a need of the MVC pattern in Android.

It provides an easy way to modify code and also help in unwanted issues. Those come in simple Android design patterns.
If you would like to implement MVC on Android, then follow this below given link and enjoy the MVC implementation techniques in your project.

http://www.therealjoshua.com/2011/11/android-architecture-part-1-intro/

Questions:
Answers:

According to the explanation that the Xamarin team explained (on the iOS MVC “I know it seems weird, but wait a second”):

  • The model (data or application logic),
  • The view (user interface), and
  • The controller (code behind).

I can say this:

The model on Android is simply the parcelable object. The view is the XML layout, and the controller is the (activity + its fragment).

*This is just my opinion, not from any resource or a book.

Questions:
Answers:

There is not an implemented MVC architecture, but a set of libraries / examples exists to implement an MVP (model–view–presenter) architecture.

Please, check these links:

Google added an example of an Android architecture MVP:

Questions:
Answers:

When we apply MVC, MVVM, or Presentation Model to an Android app, what we really want is to have a clear structured project and more importantly easier for unit tests.

At the moment, without a third-party framework, you usually have lots of code (like addXXListener(), findViewById(), etc.), which does not add any business value.

What’s more, you have to run Android unit tests instead of normal JUnit tests, which take ages to run and make unit tests somewhat impractical. For these reasons, some years ago we started an open source project, RoboBinding – A data-binding Presentation Model framework for the Android platform.

RoboBinding helps you write UI code that is easier to read, test and maintain. RoboBinding removes the need of unnecessary code like addXXListener or so, and shifts UI logic to Presentation Model, which is a POJO and can be tested via normal JUnit tests. RoboBinding itself comes with more than 300 JUnit tests to ensure its quality.

Questions:
Answers:

MVC model

Model-View-Controller in Android
In around 2011, when Android started to become more and more popular, architecture questions naturally appeared. Since MVC was one of the most popular UI patterns at that time, developers tried to apply it to Android too.

Model
The Model represents a set of classes that describe the business logic i.e. business model as well as data access operations i.e. data model. It also defines business rules for data means how the data can be changed and manipulated.

View
The View represents the UI components. It is only responsible for displaying the data that is received from the controller as the result. This also transforms the model(s) into UI.

Controller
The Controller is responsible to process incoming requests. It receives input from users via the View, then process the user’s data with the help of Model and passing the results back to the View. Typically, it acts as the coordinator between the View and the Model.

in other word

Models: Content Providers.
Data Managers that are the recommended form of inter-application data sharing.

Views: Activities.
This is the application’s primary user interface component. Every individual screen of an Android application is derived from the Activity Java class (android.app.Activity).
They are containers for Views (android.view.View).

Controllers: Services.
These are background components that behave like UNIX daemons and Windows services. They run invisibly and perform ongoing unattended processing.