Android application architecture - what is the suggested model? [closed] - android

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
In the same way a web or desktop app might have three or n tiers - UI, Business, Data for example - what is the suggested structure for an Android application? How do you group classes together, what layers do you have etc?
I'm just starting Android dev (an internet-based app that must respond to incoming notifications) and have no real feel for the structure I'm aiming at. Suggestions appreciated.

IMHO, Android "wants to" follow a MVC pattern, but view & controller are generally really coupled in activities.
It makes unit test harder and it's hard to obey to the Single Responsibility Principle.
I found a really nice Android architecture presented here, there could be an idea. Everything is loosely coupled, so much easier to test and edit.
Obviously, I'm sure there are a lot of others possibilities (like the MVP pattern (Model View Presenter) - and here are answers talking about MVP in Android), but you should still take a look on it.

I've been working on Android for 9 months now from a server-side background where full unit testing and layered architectures are common and work well.
Through lots of trial and error and I would strongly suggest using the Model View Presenter pattern, not Model View Controller.
A huge issue I've found is that Activities/Fragments have a lifecycle which is outside your control and can lead to unexpected issues.
For example, our main android app wants to be used in landscape mode on tablets. We do this in OnCreateView() or OnCreate().
On a Nexus 7, the default view is portrait so what happens is that it starts the activity in portrait mode, our code then says go to landscape and android ultimately creates the activity class 3 times!
We've hooked up network requests to onCreate and they end up happening 3 times in this case.
Sure, we can add logic to look for duplicate calls but, in my opinion, it would be better, architecturally to try and divide the UI from the business logic.
My recommendation would be to use the factory pattern to create presenters from the activity but make sure the factory only ever returns the same instance. The presenter can then contain logic to do network request, look for duplicates and return cached results and general business logic.
When results from network calls return, either post to a bus such as Otto which the activity (register for the event on onResume() and deregister during onPause()) has registered to, or make sure the callback interface implemented by the activity has been updated to the last activity in the presenter.
This way, code in the presenter downwards is unit testable and not reliant on flaky UI layer testing.

The actions, views and activies in Android are the baked in way of working with the Android UI and are an implementation of a model-view-viewmodel pattern, which is structurally similar (in the same family as) model view controller.
To the best of my knoweledge, 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.
You can find MVC in the followings:
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 store data in SQLite or your custom data in /assets/ folder, read more about resources and assets
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 model, and have your own packages, that will act as a structure
A lot of Utils have been already written for you. DatabaseUtils, Html,
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 oppinion are the activites 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 this things in your code, then your anyway following a MVC pattern.

MVP is the latest architecute most people are following
Here is the small documentation As Uncle Bob's clean architecture says, “Architecture is About Intent, not Frameworks”
Watch this video it's just mindblowing good.

Here is a dedicated project for Android Architecture blueprints with well documented source codes. All of them are based on the MVP pattern with several twists. Also check the comparison of the various solutions based on lines-of-code, testability, cost of learning, their support for increasing data complexity. It depends on the particularly developed app and the context (time to market, developers, future plans, etc.) which blueprint fits best.

Related

Android MVP: is it just an excuse to enable testing? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I honestly cannot get my head around all this MVP and similar stuff with respect to Android: What is its real point?
Up until now the only practical reason I see to use MVP in Android is to 'extract' unit-testable pieces of code from framework classes (i.e. Activities, Services, Fragments...) which would otherwise be difficult (or impossible) to test.
This is nice but this way Activities (and other framework classes) end up delegating work to the presenter when possible (i.e. when dealing with framework agnostic code) and doing work directly when not. Because of this Presenters end up looking somehow bizarre by having methods which mirror the Activity lifecycle ones (onStart, onResume, clickListeners...). I wonder if this is a code smell?
On top of this I see a ton of libraries/patterns to build MVP Android apps but I honestly don't see their real benefit: what is the downside of having each Activity creating and managing its own presenter manually?
I see no benefit in decoupling the Activity and the Presenter from each other, since the presenter is merely the 'extraction' of some code from the Activity it will be tightly coupled to it by definition and this sounds to me fine as long as the presenter contains only strictly presentation logic (the rest of the business logic shall go into dedicated classes which don't know anything about the View/Presenter duo).
I'm feeling a bit lost in this topic and I'd like some other opinions on the matter to gain a greater perspective.
From long term perspective your code should be feasible and easily maintainable, No one want to spend extra time to refactor code.No, when we starting our project we should thing about proper patterns to do.
Talking about MVP it provides you the presenter layer which can be easily testable and there is no view reference so you can easily perform junit test cases otherwise you have to use other UI test cases.
you can reuse same presenter anywhere you want as it contains only business logic
so, my suggestion you should go ahead with MVP if you don't wanna face future code problem
Yes, sure, you can make you presentation logic framework-agnostic for testing, but MVP also helps to change the behaviour at runtime by changing presenters. View interface should have bit more abstract methods (not 'hide button X', describing , say, displaying a set of data). By decoupling the UI logic from the framework-dependent implementation, we can use different Views for changing UI, or Presenter for changing logic at runtime. View - Presenter is also a 'shim', which makes it harder to write 'spaghetti' code

Android Architectural patterns [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have just started with the android development and I am trying to develop my first application, which I am actually going to publish. I have a programming background in Java and knowledge of some patterns however I have no idea which patterns I should stick with while developing android apps. Also where to put Threads. I am developing an app, which constantly loads data from a remote database through PHP scripts and displays them on UI. I divided an app to few layers - Presentation layer, Domain Layer/Service Layer and Data Source Layer. Between them I create facades to access the services of the layer bellow. I dont really know if I should stick with this structure or completely rebuild this app according to some other patters. Its better to find it out at the beginning of the development than to be forced to rebuild entire application later on. So if somebody could provide me with some links about architectural patterns which I can use or write something short about it here, I would really appreciate it!
In my opinion the single responsibility principle and separating whole application into different layers (such as MVC pattern but Android is not fully compatible with formal MVC) is a good practice in Android development.Now I will talk about major layers in the following:
Representation layer :
For instance Android framework offers a very straightforward XML representation for Presentation layer,In regard to this XML representation, you should not create the user interface stuff in code. Instead, you must do it by XML.
Application Logic layer:
For application logic layer it is good to accomplish it in code, not anywhere else, For example there is a android:onclick="function_name" attribute in Android XML(for assigning an onClickListener to a View) But as MVC pattern the View/representation layer MUST be fully separated from Controller/logic layer.
Data source layer :
Finally you can have a data source layer which its responsibility is to providing data, persisting data, and all data related stuff. In Android you would put some things in this layer such as dealing with SQLite, ContentProviders, SharedPreferences etc
Result:
I think it's better to pick a main architecture pattern and design your application in high abstraction level according to your picked pattern and then implements its sub-layers. my favorite approach for architectural design and implementation is something sounds like top-down approach, in this strategy you would design your application in top to bottom manner / more abstract to less abstract / less detail to more detail
I divided an app to few layers - Presentation layer, Domain Layer/Service Layer and Data Source Layer.
Alternatively you could divide the app vertically by its features. So you get a package for each feature or activity, perhaps with subpackages. A good rule of thumb is: a package should not contain more logic, than you (or someone else) can easily understand. This technique has some advantages. First, your packages do not become bigger and bigger when you add more features to your app. Second, it becomes easier to maintain dependencies between different features. Perhaps your IDE can generate a dependency matrix of your packages.
Also where to put Threads. I am developing an app, which constantly loads data from a remote database through PHP scripts and displays them on UI.
Android has the concept of Loaders and AsyncTasks. They help you to seperate long running tasks from the UI. There is an example using the Loader-API on the Android developer website.
You might want to put your network communication in a Service instead of AsyncTask or Thread.
Your architecture sounds like some form of MVC which is good in my opinion.
I think the Activity is a good starting point for you. Learn it's lifecycle and how to present your data to the user. You can also read more about threads and connectivity to see for yourself how it's done in android.

Android MVC Model [duplicate]

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?
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.
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.
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.
After some searching, the most reasonable answer is the following:
MVC is already implemented in Android as:
View = layout, resources and built-in classes like Button derived from android.view.View.
Controller = Activity
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.
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.
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:
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.
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.
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)
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
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.
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
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.
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.
Model View Controller (MVC)
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
It was surprising to see that none of the posts here answered the question. They are either too general, vague, incorrect or do not address the implementation in android.
In MVC, the View layer only knows how to show the user interface (UI). If any data is needed for this, it gets it from the Model layer. But the View does NOT directly ask the model to find the data, it does it through the Controller. So the Controller calls the Model to provide the required data for the View. Once the data is ready, the Controller informs the View that the data is ready to be acquired from the Model. Now the View can get the data from the Model.
This flow can be summarised as below:
It is worth noting that the View can know about the availability of the data in the Model either through Controller -- also known as Passive MVC -- or by observing the data in the Model by registering observables to it, which is Active MVC.
On the implementation part, one of the first things that comes to mind is that what android component should be used for the View? Activity  or Fragment ?
The answer is that it does not matter and both can be used. The View should be able to present the user interface (UI) on the device and respond to the user's interaction with the UI. Both Activity  and Fragment  provide the required methods for this.
In the example app used in this article I have used Activity for the View layer, but Fragment  can also be used.
The complete sample app can be found in the 'mvc' branch of my GitHub repo here.
I have also dealt with the pros and cons of MVC architecture in android through an example here.
For those interested, I have started a series of articles on android app architecture here in which I compare the different architectures, i.e. MVC, MVP, MVVM, for android app development through a complete working app.
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.
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)
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.
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:
https://github.com/sockeqwe/mosby
https://github.com/android10/Android-CleanArchitecture
https://github.com/antoniolg/androidmvp
Google added an example of an Android architecture MVP:
https://github.com/googlesamples/android-architecture
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 i don't Google will ever forcefully impose the restrictions of an MVC implementation like iPhone, but its upto the developers which patteren or technique they want in their project, In small or simple applications use of MVC is not required, but as the application grows and get complicated and require modification's of its code in later years, then there comes a need of the MVC pattern in Android.
It provides an easy way to modify code and also helps in reduction of issues.
If you would like to implement MVC on Android, then follow this below given link and enjoy the MVC implementation in your project.
http://www.therealjoshua.com/2011/11/android-architecture-part-1-intro/
But nowadays i think MVP along with Android Architectural Pattern is one of the best option developers should use for a clean and robust android applications.
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.
In my understanding, the way Android handles the MVC pattern is like:
You have an Activity, which serves as the controller. You have a class which responsibility is to get the data - the model, and then you have the View class which is the view.
When talking about the view most people think only for its visual part defined in the xml. Let's not forget that the View also has a program part with its constructors, methods and etc, defined in the java class.

Which Architecture patterns are used on Android? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm doing a small research of mobile platforms and I would like to know which design patterns are used in Android?
e.g. in iOS Model-view-controller is very widely used together with delegation and other patterns.
What patterns and where in particular does Android use?
EDIT
I'm not asking for design patterns used deep in kernel, dalvik and so on, but about patterns which an application developer will meet while developing an application.
I tried using both the model–view–controller (MVC) and model–view–presenter architectural patterns for doing android development. My findings are model–view–controller works fine, but there are a couple of "issues". It all comes down to how you perceive the Android Activity class. Is it a controller, or is it a view?
The actual Activity class doesn't extend Android's View class, but it does, however, handle displaying a window to the user and also handle the events of that window (onCreate, onPause, etc.).
This means, that when you are using an MVC pattern, your controller will actually be a pseudo view–controller. Since it is handling displaying a window to the user, with the additional view components you have added to it with setContentView, and also handling events for at least the various activity life cycle events.
In MVC, the controller is supposed to be the main entry point. Which is a bit debatable if this is the case when applying it to Android development, since the activity is the natural entry point of most applications.
Because of this, I personally find that the model–view–presenter pattern is a perfect fit for Android development. Since the view's role in this pattern is:
Serving as a entry point
Rendering components
Routing user events to the presenter
This allows you to implement your model like so:
View - this contains your UI components, and handles events for them.
Presenter - this will handle communication between your model and your view, look at it as a gateway to your model. Meaning, if you have a complex domain model representing, God knows what, and your view only needs a very small subset of this model, the presenters job is to query the model and then update the view. For example, if you have a model containing a paragraph of text, a headline and a word-count. But in a given view, you only need to display the headline in the view. Then the presenter will read the data needed from the model, and update the view accordingly.
Model - this should basically be your full domain model. Hopefully it will help making your domain model more "tight" as well, since you won't need special methods to deal with cases as mentioned above.
By decoupling the model from the view all together (through use of the presenter), it also becomes much more intuitive to test your model. You can have unit tests for your domain model, and unit tests for your presenters.
Try it out. I personally find it a great fit for Android development.
Update November 2018
After working and blogging about MVC and MVP in Android for several years (see the body of the answer below), I decided to capture my knowledge and understanding in a more comprehensive and easily digestible form.
So, I released a full blown video course about Android applications architecture. So, if you're interested in mastering the most advanced architectural patterns in Android development, check out this comprehensive course here.
This answer was updated in order to remain relevant as of November 2016
It looks like you are seeking for architectural patterns rather than design patterns.
Design patterns aim at describing a general "trick" that programmer might implement for handling a particular set of recurring software tasks. For example: In OOP, when there is a need for an object to notify a set of other objects about some events, the observer design pattern can be employed.
Since Android applications (and most of AOSP) are written in Java, which is object-oriented, I think you'll have a hard time looking for a single OOP design pattern which is NOT used on Android.
Architectural patterns, on the other hand, do not address particular software tasks - they aim to provide templates for software organization based on the use cases of the software component in question.
It sounds a bit complicated, but I hope an example will clarify: If some application will be used to fetch data from a remote server and present it to the user in a structured manner, then MVC might be a good candidate for consideration. Note that I said nothing about software tasks and program flow of the application - I just described it from user's point of view, and a candidate for an architectural pattern emerged.
Since you mentioned MVC in your question, I'd guess that architectural patterns is what you're looking for.
Historically, there were no official guidelines by Google about applications' architectures, which (among other reasons) led to a total mess in the source code of Android apps. In fact, even today most applications that I see still do not follow OOP best practices and do not show a clear logical organization of code.
But today the situation is different - Google recently released the Data Binding library, which is fully integrated with Android Studio, and, even, rolled out a set of architecture blueprints for Android applications.
Two years ago it was very hard to find information about MVC or MVP on Android. Today, MVC, MVP and MVVM has become "buzz-words" in the Android community, and we are surrounded by countless experts which constantly try to convince us that MVx is better than MVy. In my opinion, discussing whether MVx is better than MVy is totally pointless because the terms themselves are very ambiguous - just look at the answers to this question, and you'll realize that different people can associate these abbreviations with completely different constructs.
Due to the fact that a search for a best architectural pattern for Android has officially been started, I think we are about to see several more ideas come to light. At this point, it is really impossible to predict which pattern (or patterns) will become industry standards in the future - we will need to wait and see (I guess it is matter of a year or two).
However, there is one prediction I can make with a high degree of confidence: Usage of the Data Binding library will not become an industry standard. I'm confident to say that because the Data Binding library (in its current implementation) provides short-term productivity gains and some kind of architectural guideline, but it will make the code non-maintainable in the long run. Once long-term effects of this library will surface - it will be abandoned.
Now, although we do have some sort of official guidelines and tools today, I, personally, don't think that these guidelines and tools are the best options available (and they are definitely not the only ones). In my applications I use my own implementation of an MVC architecture. It is simple, clean, readable and testable, and does not require any additional libraries.
This MVC is not just cosmetically different from others - it is based on a theory that Activities in Android are not UI Elements, which has tremendous implications on code organization.
So, if you're looking for a good architectural pattern for Android applications that follows SOLID principles, you can find a description of one in my post about MVC and MVP architectural patterns in Android.
When i reach this post it really help me to understand patterns with example so i have make below table to clearly see the Design patterns & their example in Android Framework
I hope you will find it helpful.
Some useful links for reference:
Common Design Patterns for Android with Kotlin
Introduction to Android Design Patterns
Design Patterns
There are various patterns used in Android framework like:
Broadcast receiver uses Observer pattern
Remoter service invocation uses Proxy pattern
View and view group uses Composite pattern
Media framework uses Facade pattern
Here is a great article on Common Design Patterns for Android:
Creational patterns:
Builder (e.g. AlertDialog.Builder)
Dependency Injection (e.g. Dagger 2)
Singleton
Structural patterns:
Adapter (e.g. RecyclerView.Adapter)
Facade (e.g. Retrofit)
Behavioral patterns:
Command (e.g. EventBus)
Observer (e.g. RxAndroid)
Model View Controller
Model View ViewModel (similar to the MVC pattern above)
The Following Android Classes uses Design Patterns
1) View Holder uses Singleton Design Pattern
2) Intent uses Factory Design Pattern
3) Adapter uses Adapter Design Pattern
4) Broadcast Receiver uses Observer Design Pattern
5) View uses Composite Design Pattern
6) Media FrameWork uses Façade Design Pattern
In the Notifications case, the NotificationCompat.Builder uses Builder Pattern
like,
mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentTitle(getString(R.string.notification))
.setContentText(getString(R.string.ping))
.setDefaults(Notification.DEFAULT_ALL);
Android also uses the ViewHolder design pattern.
It's used to improve performance of a ListView while scrolling it.
The ViewHolder design pattern enables you to access each list item view without the need for the look up, saving valuable processor cycles. Specifically, it avoids frequent calls of findViewById() during ListView scrolling, and that will make it smooth.
All these patterns, MVC, MVVM, MVP, and Presentation Model, can be applied to Android apps, but without a third-party framework, it is not easy to get well-organized structure and clean code.
MVVM is originated from PresentationModel. When we apply MVC, MVVM, and 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 an 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 the 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.
I would like to add a design pattern that has been applied in Android Framework. This is Half Sync Half Async pattern used in the Asynctask implementation. See my discussion at
https://docs.google.com/document/d/1_zihWXAwgTAdJc013-bOLUHPMrjeUBZnDuPkzMxEEj0/edit?usp=sharing
In Android the "work queue processor" pattern is commonly used to offload tasks from an application's main thread.
Example: The design of the IntentService class.
The IntentService receives the Intents, launch a worker thread, and stops the service as appropriate.All requests are handled on a single worker thread.
Binder uses "Observer Pattern" for Death Recipient notifications.

what's design pattern principle in the Android development? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I was a JaveEE developer. Recently I joined an Android development team. The structure of Android confused me. The MVC design pattern doesn't seem to suit for Android development. So what is the design pattern principle for Android development? I mean is there any hint about how to write a clean, easy reading and effective Android code.
Android's architecture annoyed me at first, but I beginning to see a method to their madness. It's poorly explained by the android documentation. My biggest gripe has always been that it's hard to have a centralized data model with objects that your Activities share just like a normal application. Android seemed to want me to be a nomad because I could only share primitives between my Activities. And dropping junk in a database is NOT a model because it contains no behavior. So as most people my business logic all ends up in my activity making it hard to share business logic in other activities.
I've come to find out I was missing some key puzzle pieces. Android is MVC. However, it's coupled to the View fairly heavily.
Activity == Controller
Model == Subclass of Application
Anything that subclasses View == View
Interestingly you can create a subclass of Application and declare this in your Manifest file, and Android will create a single instance of this object that lives the length of your application no matter what Activity is destroyed or created. That means you can build a centralized data model there that all Activities have access to.
The way I see this is something like a primitive Spring container that you can initialize objects and resolve dependencies between them. That way you can decouple the model portion of your application away from the Activity themselves. And just have the Activity make calls on the model, and hand callbacks to receive the results so it can update the UI.
The problems with Android is that it mixes controller and view pretty heavily. For example, subclasses like TabActivity, ListActivity imply a certain view being used. So swapping out a view is pretty involved. Also the Controller makes very specific assumptions about what the view is even if you use Activity. He contains direct references to UI objects like TextView, etc. And it registers for low level events like clicks, keyboard, etc.
It would be better if Activity could register for more high level events like "Login", "Update Account Balance", etc which the view would dispatch in response to a series of clicks, keyboard, touch events. That way the controller works at the level you might describe features instead of design features.
I think we'll reach this type of design eventually as we better understand come up with better tools and techniques. It seems like Android might have the extensibility to make this happen, but it's up to community to chart it.
The actions, views and activies in Android are the baked in way of working with the Android UI and are an implementation of a model-view-viewmodel pattern, which is structurally similar (in the same family as) model view controller.
To the best of my knoweledge, 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.
You can find MVC in the followings:
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 store data in SQLite or your custom data in /assets/ folder, read more about resources and assets
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 model, and have your own packages, that will act as a structure
A lot of Utils have been already written for you. DatabaseUtils, Html,
There is no single MVC Pattern you could obey to. MVC just states more or less that you shouldn't 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 activites 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 this things in your code, then you're anyway following a MVC pattern.
Android development is primarily GUI development, which like Swing/AWT in Java consists of lots of anonymous inner classes reacting to GUI events. Its one of the things that has really kept me away from doing a lot with Swing....but I have an Android phone, so I'm going to grit my teeth and just get over it, as many an Apple fanboy has said about the antenna problems. ;)
Android makes the typical decision of making the Controller and the View a single class. This encourages putting too much in the same place. An Activity corresponds to a screen, each View to a region of a screen (sometimes the whole screen), each Controller to the user gestures from that region of the screen, and Models are just Models, sometimes backed by services from Environment or some other crazy little set of utility functions. I use the Activity to coordinate one or more MVC trios. This helps deal with Android's choice to just throw everything in the same place.
I can test the vast majority of an Android app without running the simulator. Big win.
Sorry for my English.
Android has a very good modularity (Activities, Fragments, Views, Services, etc.). So there is no need in MVC.
Of course there is the separation of taking input (Activities, Fragments), logic, view (xml or java) and data (databases, files, preferences). But this is not MVC. You shouldn't try to use MVC, it will only complicate your architecture.
Rather than keeping something in global scope, Android motivates you to keep objects as deep as possible in their scopes (class members, local variables), and pass objects to/from activities, or to fragments, using Intents/Bundles. This is also because of memory limitation.
The system may destroy your activity if the foreground activity
requires more resources so the system must shut down background
processes to recover memory.
So it's not safe to store not-constant (mutable) objects as global (static) objects. Usually you use static for immutable constants.
In simple terms, you separate your application into screens (Activities). Then each screen - into fragments (Fragments). To perform a sequence of actions on the screen you can also separate them using Fragments (example).
So you have very small blocks in your application, each of which you can easily test and reuse.
My impression is that android programming model has lots of similarity with MS WPF.
XML layout definitions, code that is always bound to one of these definitions...
So, if you are asking about design patterns because you want to improve your current or in development android projects, maybe you should look at WPF practices and patterns for improved architecture, like MVVM.
Check out these links:
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
there is small project that is already trying similar thing:
http://code.google.com/p/android-binding/
cheers

Categories

Resources