Many Android apps include a BaseActivity class of their own, which all Activities in the app extend. This is useful because it gives a central place to put functionality that's common across most/all activities. The main drawback of having a BaseActivity is you are then unable to use any of the Activity subclasses (ListActivity, etc.).
One alternative is to have an ActivityDelegate. This gives a central place for functionality while still allowing you to use Activity subclasses. It's also arguably more testable, since it uses composition instead of inheritance.
Both of these solutions potentially lead to a lot of spaghetti code when the BaseActivity/ActivityDelegate gets too large and convoluted. A possible solution to this is to use the delegate pattern, but split the functionality into many different Delegates. This reduces spaghetti code in the Delegates, but then the Activities get more complicated - they're now trying to forward their on* methods to lots of different Delegates instead of just one.
A possible solution to all of these problems is to use a Delegate Manager. The Delegate Manager keeps track of all the smaller Delegates in the app. Activities forward their on* methods to the Delegate Manager, which forwards them on to all of the individual Delegates. This accomplishes all of the following:
Dedupes code - all common functionality gets placed into one of the Delegates
Allows use of Activity subclasses
Simple code in all Activities - all on* methods are forwarded to just one class
Easily testable - it's simple to mock out everything around the Delegates and the Delegate Manager for unit tests
Has anyone tried using this pattern before? If so, how did it go?
As far as I understand, you're talking about one single DelegateManager object for the entire application. If this is the case, you can use registerActivityLifecycleCallbacks, see http://developer.android.com/reference/android/app/Application.html#registerActivityLifecycleCallbacks%28android.app.Application.ActivityLifecycleCallbacks%29
If you're on < API level 14 you need to take a look at: https://github.com/BoD/android-activitylifecyclecallbacks-compat.
registerActivityLifecycleCallbacks lets you hook into the activities onXXX lifecycle methods.
Doing this certainly has all the benefits you described:
decoupling being usable only when you actually need to repeat behavior which is kinda seldom for controller+view logic tied in together the way Activity works.
Removing inheritance is nice if you have activities you might reuse - but I've never had to do it before. But I guess a good use-case would be your home-cooked activity for handling settings or something like it that needs app-wide L&F & behavior.
On the top of my head I can think of these downsides:
Using listeners all over the place can blur path of the application activity/call hierarchy and can make the code hard to understand. This holds true for all listener/dispatcher type of programming. It's a powerful tool, but handle it with care.
It can introduce a lot of (as you mention) boilerplate/spaghetti code if all you do is pass on to lifecycle listeners/delegates.
it is your responsibility to de-register yourself from the Application with Application.unregisterActivityLifecycleCallbacks. I don't think there's a good way around it,
Personally I haven't used this design-pattern much for lifecycles, but it might be worthwhile for some use-cases. For example:
ApplicationLifecycleLogger: Every time you create/resume/pause... an activity, you logcat or something else making debugging lifecycles a tad bit easier.
If for example someone goes into an activity he/she is not allowed to go into due to model state of some sort (e.g. a ringing alarm -> can't go into AlarmEditActivity), you could do finish() there.
Passing object state across activity boundaries without Parcelable:s and screen rotation changes. Usually this is implemented with a Map in Application or some static field somewhere. You can do this by letting the delegators hold state.
Also, take a look at: Is there a design pattern to cut down on code duplication when subclassing Activities in Android?
I hope this was helpful =)
Related
Recently I took over an android project which is built on top of MVP. While simple screens are quite straight forward and easy to read and maintain, the more complex parts of the app are not. Multiple inheritance levels have caused me days of switching between classes, trying to find out how the information flow is actually working.
Here one example of the more problematic hierarchies:
Since we use MVP, naturally there is another presenter class and another view class for each of the classes in the diagram.
So I did some research and found this article: Composition vs Inheritance in MVP
and it's basically saying that composition should be favoured over inheritance in this situation.
What it isn't saying is how to apply that in android. I thought about it for a while, but can't come up with a nice pattern. I could do custom views, but how would they use presenters in the end?
Inheritance, although quite powerful, is quite easy to misuse, and when the inevitable happens, i.e change in requirements, inheritance is highly susceptible to break the open-closed principle due to its inflexibility. The programmer is bound to modify the existing classes which in turn breaks the client code.
This is the reason why composition is usually favored over inheritance. It provides more flexibility with changing requirements.
This design principle says exactly that:
Encapsulate what varies.
Identify the aspect of your code that varies and separate them from
what stays the same. This way we can alter them without affecting the rest of the code.
Moving on to your problem, the first thing that came to my mind after I read your question was: Why not use Strategy Pattern!
The approach you can take is:
BaseMapViewFragment will contain all the code that is common to all derived classes. Have separate Interfaces for different kinds of behaviors(things that vary). You can create concrete behavior classes according to your requirements. Introduce those behavior interfaces as class fields of BaseMapViewFragment. Now classes that extend the BaseMapViewFragment will initialize the required behaviors with concrete behavior classes.
Whatever I said in the above paragraph might be confusing (my english isn't that good either :D), but I just explained the working of the Strategy pattern, nothing more.
There is another design principle at play here:
Program to an interface, not an implementation. The Strategy pattern uses it to implement the code that varies.
I've been in a similar situation. What I ended up doing was taking out functionality from "Base" into separate classes then use it as composition. It was also related to using Maps in a similar structure.
You can create a new class MyAppMapView, it could extend a FrameLayout (or whatever best for your layout). This can contain all of your Map related code (including MapView), you can have custom MapView related functions here like onStart(), onResume(), onPause(), onStop(). Also, you can put everything related to maps here like markers, lines etc.
Once you have that in place you can just use new MyAppMapView() (or add it in xml using com.example.MyAppMapView) in your MapViewSimpleFragment and MapViewDetailsFragment and since both of these classes would be composing your custom MyAppMapView class, you can call all map related functions from Fragments like drawing markers, lines, onStart() etc.
I'm currently attempting to convert my existing Android app to using Fragments. The main work that my activity does can sometimes take a while, so I implemented some Threads to act as callback handlers - I was led to believe this is best practice to use these and a progress dialog.
Hopefully that makes sense.
My question is: should I move those inner classes to my Fragment class, or keep them in my Activity class?
That depends how many fragments you have and what you're trying to do with those threads. While there is no general rule, here are two things to consider in making your decision.
(1) If you're doing something like downloading information that's going to be used in multiple fragments (say in a ViewPager or Tab set up) it might make sense to have the callbacks in your FragmentActivity this way you can easly distribute that information to the Fragment that will be handling the UI. Another example that comes to mind would be fetching location data. If the location data is going to be used throughout the app, and your FragmentActivity is hosting multiple fragments, it makes more sense to get the information in one place and simply update the fragments individually.
(2) If you're using something like AsyncTask for one-off downloads, posts, or other things unique to a specific fragment, there's nothing wrong with keeping it localized to that fragment. In fact, in that case, it would be less efficient to off load the task to your FragmentActivity than to complete the task localy.
Really there's not "right" answer. Just a question of how your app is structured and what you're trying to acomplish.
Actually the best practice for software in general is a little different, first of all you need to know that there's no "Hard Rules" to anything in software, the keyword is "All Depends(Taken from book Pragmatic Thinking and Learning)" and as such, it all depends on what you want and what you need, you should put things on a balance to know where is better for you, but going back to the best practice in general for these cases the best is to have a Business Model Class completely decoupled from either Fragment/Activity or any other android component, you are actually supposed to have a Model Class and together with a Controller Class, both of them should manipulate/populate the data and views within those elements...
Hope this helps.
Regards!
There's no hard and fast rule, but I like keep them in the scope within which they most naturally fit. If the result of a long running task is only useful within the fragment which initiated it then it lives in the fragment. If the task may affect multiple fragments then it might live in the activity.
I’m not an Android pro though I’ve developed an app consisting of more than 50 activities which makes the app really large. After 8 weeks of developing, now there are problems which caused the app difficult to maintain and upgrade.
Major ones I’m dealing with are
I cannot pass object reference to activities’ constructors. In fact I found the mechanisms of startActivityForResult – Intent – onActivityResult really limiting and results in dirty code of many constants for actions per activity and a lot of switch case that is really hard to follow the flow of app.
Another problem is that I do not know how to manage the life cycle of the whole app as each activity has its own life cycle.
I had some successful experience with LWUIT and J2ME – polish which ignore J2ME MIDlets (similar to android activity) and implement their own architecture and windowing system with just one MIDlet as entry to the app. I’ve come up with the same idea for android.
To clarify, I’m thinking of an app with just one main Activity and other activities implemented as objects which extend View object and these views can be dynamically added to main activity FrameLayout and stack on each other. Activities’ logic can be implemented in such classes and I've even found a way to implement dialogs in this way.
Business and state objects can be passed to their constructor and it sounds good ignoring its side effect of writing a little more code. This way listeners can also be passed to views’ constructors which makes app UI switch and flow management easier.
But the questions are:
Is it a good practice?
Wouldn't it lead me to performance or memory issues?
I'm also aware of
Android: What is better - multiple activities or switching views manually?
Don't Overload a Single Activity Screen
Pattern one activity, multiple views. Advantages and disadvantages
None of these clearly address the issues regarding performance or practice with reasonable evidence or documented reference
Please someone help me with this
There are popular apps in market with only one or a few activities. They use fragments and switch them. I would prefer fragments over your approach. Although I think fragments are too complex for many purposes, for your use case it would be a good solution. Your UI behavior should be in fragments, and your activity is the controller part transferring data between your fragments. Fragments also have an own life cycle.
I don't like startActivityForResult either. If I have a set of activities - all providing data - and I don't know in which order they will be called, I prefer to use a singleton class then using intents for data transmission between activities. But you have to analyze your problem to get a good solution.
There is already an MVC framework built, PureMVC library.
I was wondering if instead of having to create a new class for each activity is it possible to create mulitiple activities within one class?
So define various layout xml for various activities within one class, instead of having to create new classes for each activity.
Thanks
No, you should put each activity in seperate class. Take a look at this question. Someone is wondering just the same thing as you.
Ricky,
Yes, you may have multiple "Activities" defined inside a single class. But there are a lot of obstacles and issues with doing so. Before I answer this question, two things must be understood:
What you are asking goes against the Android guidelines for development, and those guidelines are enforced in as many ways as they can be during the compilation process, so nothing I say here is insured to work across any or all API versions of the Android SDK.
Different development environments do their own checks and compile in slightly different ways. I will be speaking from the Eclipse side of development.
Techniques listed here are for education, but introduce a lot of issues. For self education and theory, it is a wonderful practice to explore. However, the goal of this answer is to educate you as to why the guideline should be followed rather than sidestepped.
Requirements for an Activity
The first thing to understand is that Android has specific points that must be met for an Activity to be run. It must: a) be declared in the manifest; b) have an intent-filter describing how it is to be used; c) be a public class; d) be a top-level class.
Multiple Activities, Same Parent Class
This means that you may create an Activity inside of another class (an inner Activity, so to speak), but it must be declared static and public. This limits your Activity in a huge number of ways. Calls to methods or members that are instance-related (not static) to the parent class are not possible. So you lose a lot of time and code hacking around this.
Second, it affects your Android XML declaration for your Activity. This is where the real trouble comes in, because while it can be done, it is very specific and there is not any supporting documentation to make that happen. But that's okay, you wanted to know if you could make ONE class for your Activities.
Multiple Activities, Same Class
Well, Android determines which Activity to run based on its Intent. You could declare the same class multiple times, but with different Names and Intent-filters. If this is the case, then you would have to determine what to do based on the Intent and the extras included. This would be done in your onCreate() method.
Doing things in this manner would mean that you would have to code for two Activities in every place that you would normally deal with one. This would make it much harder to track down bugs to support your product. It would also make every routine operation take longer as you would have to decide which method to perform. For instance, if you overrode onDraw(), you would have to know which Activity you were drawing. Its ultimately just a big schmorgasborg (sp? does anyone know how to spell that word?) of "what do I do?!"
The Real Question
Why would you want to do this anyway?
1. If the answer is to save yourself time navigating your own project, believe me... That won't really happen. Your code will be harder to read, interpret and debug.
If the answer is that you want to save file space, I would reconsider your project's priorities.
If the answer is that you want to share functionality, consider extending Activity and then extending your new sub class. How do you think they made the ListActivity or TabActivity to begin with?
If you want to save state, you can place state in SharedPreferences or your Application object (if you have extended it).
As you can see, no matter your needs, there are many other ways to go about it in a way that doesn't cause you or anyone else a hassle.
Hope this helps,
FuzzicalLogic
This pattern is similar to the pattern Main Servlet (the Front Controller) that is used for developing web applications.
The main idea of this pattern: we have one Activity that manages multiple views and this activity is responsible for representing current content. Not all views need functional of activity (e.g. life-cycle methods) so the main question is: if I can go without activity why do I have to use it?
I have found the following disadvantages of using this pattern:
Official source doesn't recommend to Overload a Single Activity Screen
but they don't explain why.
We cannot use TabActivity, ListActivity, MapActivity. But there are some tricks to go without them.
If different screens have different menu it's a problem to make that without activities.
It is necessary to keep history by ourselves. But it's not so difficult to develop.
I have found the following advantages of using this pattern:
It's faster to change the content of current activity than to start another activity
We are free to manage history as we want
If we have only one activity-context it's simpler to find and solve problems with memory leaks
What do you think about this pattern ? Could you provide any other advantages/disadvantages ?
We cannot use TabActivity, ListAcivity, MapActivity. But there are some tricks to go without them.
You have to use MapActivity if you want to use MapView. You have to use PreferenceActivity if you want to use preference XML.
It is necessary to keep history by ourselves. But it's not so difficult to develop.
The difficulty in managing your own history will depend greatly on what the history needs to be. Implementing history for a simple wizard will be fairly easy. However, that is a particularly simple scenario. There is a fair amount of history management code in Android that you would have to rewrite for arbitrary other cases.
You also forgot:
#5. You will be prone to leak memory, because you will forget to clean up stuff, and Android will not clean up stuff (since it assumes that you will be using many small activities, the way they recommend).
#6. Your state management for configuration changes (rotation, dock, SIM change, locale change, multiple displays, font scale) will be more complicated because now you also have to figure out what extra stuff (e.g., history) need to be part of the state, and you have deal with all of them at once rather than activity-at-a-time.
#7. Having multiple entry points for your application becomes more challenging (e.g., multiple icons in launcher, app widget linking to some activity other than the main one, responding to etc.).
It's faster to change the content of current activity than to start another activity
For most modern Android devices, the speed difference will not be significant to most users, IMHO.
If we have only one activity-context it's simpler to find and solve problems with memory leaks
Except that you still have more than "one activity-context". Remember: your activity, large or small, is still destroyed and recreated on configuration changes.
What do you think about this pattern ?
Coase's "nature of the firm" theory says that businesses expand until the transaction costs for doing things internally become higher than the transaction costs for having other firms do the same things.
Murphy's "nature of the activity" theory says that the activity expands until the transaction costs of doing things internally become higher than the transaction costs for having other activities do the same things. Android developers will tend towards a "user transaction" model for activities -- things that are tightly coupled (e.g., steps in a wizard) will tend to be handled in single activity, and things that have little relationship (e.g., browse vs. search vs. settings vs. help vs. about) will tend to be handled in distinct activities.
This will be horrible to maintain if new functionality is added later on.
I'm also not convinced it will be so much faster that the user could notice.
Having components as smaller pieces that are easier to change or swap out is definitely the way to go.