I'm fairly new to Android Programming and have a question about best practice regarding how many Activities I should create.
I'm working on a Puzzle App. Currently, I have a Single Activity and around 15 Fragments(SherlockFragment).
One problem I'm experiencing is that the Activity code is becoming large and complex. Another challenge is communication between fragments.
I understand that the best practice for communication between Fragments is to create an Interface in the fragments and implement the interface in the Activity.
ref: http://developer.android.com/training/basics/fragments/communicating.html
Example:
I have a Contact fragment which contains a ListView where the user can select one or more contacts(Phone Contacts). By following the guidelines given by the link above, I could implement something like this in the Contact Fragment:
public interface OnContactSelected{
public void onContactSelected(Contact contact);
}
...
...
mCallback.onContactSelected(contact);
Then, I can listen to the selection of contacts in the Activity using code like this:
public Class PuzzleActivity extends SherlockFragmentActivity
implements ContactFragment.OnContactSelected{
...
...
public void onActivityCreated(Contact contact){
// Do something
}
The problem I'm facing is this:
The Contact fragment is an independent module used for different tasks, example:
1) Selecting a contact to add as a Friend
2) Selecting an opponent for an online game.
So the onContactSelected implementation in the Activity depends what I'm doing right now
public void onActivityCreated(Contact contact){
// if{inInAddFriendMode())doThis(); else doThat();
}
What I'm considering is to refactor the code and implement one activity for each of the main tasks in the APP, example:
FriendActivity.java ( To show and add friends)
MultiplayerGameSetupActivity.java (To configure a new game with how many players, choice of opponents, level of difficulty etc)
GameActivity.java (The game it's self)
SettingActivity.java
I'm also thinking about creating a base Activity which all of the Activities above extends.
To me this seems to solve all the problems by making the Activity code less complex, and also by allowing me to implement the Fragment interfaces cleanly in the Activities.
From your experience, is this a good approach, or should I stick to one Activity?
Thanks in advance.
I personally think it sounds like a good idea. I have found myself in the same situation as you a few times and maintaining it that way just gets more and more difficult with every addition.
The first thing I do now when I start a new project is create a Base Activity and a Base Fragment that all my others extend. I find doing it this way really helps with keeping it DRY and since everything is separated MUCH easier to maintain.
Related
In an Android app. I have a requirement where I have my HomeActivity(Having 18000 lines of code) and if my device supports ARCore, I want HomeActivity to extend with ARBaseACtivity and if device doesn't supports ARCore then i need it to extend with NonARBaseActivity.
I am checking this condition in splash screen.
Now, there is a way that first comes is that i make two activities ,same a copy of HomeActivity but i need to know is there any better way to do that. Because i don't want to copy every time i do any change in one of the HomeActivity.
Downvoters please comment below so that i can improve where i am wrong . Thanks!!
The technical answer is: not possible.
In Java, your inheritance structure is fixed. It is simply not possible to have one class C extend class A in one context, and class B in another context. When you want to do that, you would end up having two classes, C1 and C2.
The real answer of course is: you have to step back and clearly architect your whole solution. Alone the 18K lines in one whatever is an indication that something is seriously wrong here. One could mention the good old FCoI principle, but then: 18K lines of code means a lot of code and features. It is simply impossible to give you proper guidance in a single answer on stackoverflow.
So, opinionated: you should step back, and identify some (architecture) experts to talk to. Then sit down with them (probably for hours, even days), and look at what you have got, and where you want to get to. Then work together on path there. Anything else is nothing but putting band-aids on symptoms. Sure, nothing will break when you don't do that. But each step forward will simply add mess to mess, making each step more expensive. Sooner or later, changing your monolith will become close to impossible, and everybody will ask to "throw it away, and start from scratch".
As complement to the excellent answer of GhostCat, I will give you a very important hint in OOP : to enhance at runtime the behavior of an object, the decorator pattern is often a way to consider.
Here HomeActivity appears as the element to decorate and ARBaseACtivity and NonARBaseActivity appears as decorator for that.
You should define a MyActivity interface that is the base class for both decorated and decorator objects.
So things are not simple because you will have to refactor many code lines but it will make your design more flexible and with classes that have consistent responsibilities instead of having a god object as activity !
Finally in the splash screen you could define a method that returns an activity decorating the HomeActivity according to the client material detected :
public MyActivity computeHomeActivity(){
HomeActivity activity = new HomeActivity();
if (isSupportARCore()){
return new ARBaseACtivity(activity);
}
return new NonARBaseActivity(activity);
}
I have been reading up on the Android API and it seems like Fragments are meant to sort of modularize an Activity. So if an Activity has a ListView and DetailView then it should be split into two separate fragments and have the Activity act as the master controller.
In my previous project that I worked on we were using Fragments kind of like children of the Activity.
For example: Let's say there is a AutomobileActivity that is designed to save automobile input data to the cloud.
We have fragments like:
SedanFragment
TruckFragment
SportsUtilityFragment
These fragments take up the entire view of the Activity and only one is displayed at a time. While these fragments use methods in the Activity to call common webservices like saving automobile information, getting car information. They also do different things like the Truck may have an additional entry to set the "Bed Size" and SportsUtilityFragment may have "Tow Limit" etc.
So in a way we are leveraging a lot of re-use and modularizing, but it's not exactly what the Android API is detailing. Is this a bad way to use Fragments?
This is a very objective question and this will have a lot of different answers. In my opinion what you are doing is correct. The reason behind this is that they have a set of common webservices. If we go by the mvc approach they can all have the same controller(for calling webservices), a model class(Superclass- vehicle) with separate models which inherit from this vehicle model class. By doing this you can have an additional entry parameter which will be present in these models. Your view, the fragments can easily call the instance of these models. If you modularize in this manner, you will be making life very easy for yourselves.
I'm trying to learn more about proper architecture so I'm going to try to refactor some of my working code. I have an android app that swaps in a few different Fragments for the main view. Right now, the different fragments exist as properties in MainActivity. When the user picks a menu item I have to check what kind of Fragment is currently being shown (via instanceof) and perform some different tasks depending on what kind of fragment it is. It's pretty ugly and I feel like it should be better abstracted. In the future, the case statement will grow even more and need to be maintained. Also, most of the code is duplicated since I only really need to do something special for one fragment in particular. How can I abstract away these details out of MainActivity? I tried to make a base class for all my fragments but it didn't quite work out because some of the fragments extend MapFragment and some just extend Fragment. So I'm guessing an interface is the way to go but I'm not quite sure how to do it. Do I need to create an abstract factory to get these objects in MainActivity? What is the proper way to do this? After reading up a little bit on architecture, it seems to me that my MainActivity should only know about some abstractions for my Fragments and not the concrete classes themselves, is that correct? Thanks for any help you can provide.
This is a bit of a general question, but I will give a specific example for you.
I have a bunch of activities in an App. In all of the activities, there is a Facebook button. When you click the button it takes you to a specific Facebook page. I wish for the button to behave exactly the same way on every page.
Right now, in every single Activity, I create an onClickListener() for the Facebook button and make the intent and start the activity. It's the same code in every single Activity.
What is the best way to write this code once and include it in multiple activities? Is there anyway to include other .java files?
One solution that I know would work, is to make a base CustomActivity class that extends Activity and then have all activities extend CustomActivity. Then put my onClickListener() code in CustomActivity. I'm new to Java though and I wasn't sure if that was the best approach or not. Some of my Activities already extend other custom activity classes as is, so extending things that extend more things might get kinda messy, I dunno.
UPDATE
Playing the devil's advocate here: Lets say I went with the inheritance route and I create some CustomActivity that I want my Activities to extend. CustomActivity would contain a bunch of general code that I need to use for all Activities, including but not limited to the Facebook button functionality. What happens when there is an Activity that I need to use generic code from the CustomActivity but there is no Facebook button in that specific Activity?
A common base class is perhaps the best approach. (It doesn't work quite so well if some of your activities extend Activity and some extend Activity subclasses (such as ListActivity).
An alternate approach is to create a separate class that implements the logic of your click listener. This doesn't eliminate all duplicate code — each activity still needs to instantiate and register a listener — but the logic for what to do will only need to be written once in the listener class.
In either alternative, you might consider assigning the android:onClick attribute to the button. That way you don't need to register a click listener; you just need to implement the target method in each activity. This is particularly useful with the base class approach.
UPDATE
Suppose you go the inheritance route and you want an activity with no Facebook button. If you are using the android:onClick technique, then you don't have to do anything different in your code — since no button will invoke your onClick method, the method will just sit there doing nothing. If you are installing an OnClickListener in code, then you just need to test that the button exists (i.e., that findViewById() did not return null) before registering the listener.
Generally a common base class is NOT the best approach (although it's certainly valid).
This took me (and every OO programmer who "gets" OO that I know of) a while to really grok, but you should use inheritance as sparingly as you possibly can. Every time you do it you should ask yourself if there is REALLY no other way to do this.
One way to find out is to be very strict with the "is-a" test--if you call your base activity a "Facebook Activity", could you really say that each child "is" a Facebook activity? Probably not. Also if you decided to add in Twitter to some of the pages (but not others), how do you do this?
Not that inheritance is completely out! A great solution might be to extend a control to launch your facebook activity and call it a facebook button--have it encapsulate all the stuff you need to do to connect to facebook. Now you can add this to any page you want by simply dragging it on (I'm pretty sure android tools let you add new components to the pallet). It's not "Free" like extending your activity class, but in the long run it will cost you a lot less stress.
You probably won't believe me now, we all need to learn from our own experience, just keep this in mind and use it to evaluate your code as you evolve it over time.
--edit, comment response--
You can encapsulate any facebook activity you think you will use a lot in it's own class--get it to a bare minimum so you can just add it to any class in a one-liner.
At some point, however, you may decide that it's STILL too much boilerplate, I totally understand. At that point you COULD use an abstract base activity like you suggest, but I wouldn't hard-code it to handle facebook explicitly, instead I'd have it support behaviors such as facebook (and maybe others), and turn-on these behaviors as desired. You could then tell it NOT to add the facebook behavior to a given screen if you like, or add in Twitter to some of them.
You can make this boilerplate minimum, for instance if you want "Standard" functionality, you shouldn't have to do anything special, if you wish to disable facebook you might start your constructor with:
super(DISABLE_FACEBOOK_BEHAVIOR);
and if you want one that also enables Twitter you could use:
super(DISABLE_FACEBOOK_BEHAVIOR, ENABLE_TWITTER_BEHAVIOR);
with a constructor like AbstractAction(BehaviorEnum... behaviors).
This is more flexible and you actually can say that each if your activities IS-A "behavior supporting activity" with a clear conscience.
It is, of course, a perfectly good approach to be less flexible at first and refactor into a pattern like this later when you need to, just be on the look-out for your inheritance model causing problems so you don't let it mess you up for too long before you fix it.
Well, extending things is the principle of OOP, so I don't think this is a problem to have more than one level of subclasses. The solution you thought about is in my opinion the best.
Absolutely. Use inheritance to gain some reusability as you should with OOP. You'll find, as you progress, that there are gonna be more and more things you'd like to reuse in your activities -- things more complex than an onClickListener for a FB button -- so it's a great idea to start building a nice, reusable "super" activity that you can inherit from.
Greetings,
I'm currently developing an Android application, but I'd like to be able to handle button click events etc in a separate file for each Activity. Is this possible? At the moment, I have one very large file that handles all events for several Activity windows.
Any advice greatly appreciated.
Thanks in advance,
For event handling there is OnClickListener interface, you can create your own implementation and use it only in place you get the button, for example in onCreate():
#Override
public void onCreate(Bundle savedInstance) {
...
Button btn = (Button) findViewById(R.id.ok_button);
btn.setOnClickListener(new onClickListener() {
#Override
public void onClick() {
// the code
}
}
So, you don't have to create a separate file at all.
What you are trying to do is not possible (at least in a clean way).
To handle a click, you must implement one interface (View.OnCLickListener). I'm assuming clicking in a different view will produce a different type of response (i.e. one button might open a popup and another might start an activity).
Yes, you could check the id of the view that was clicked and decide what to do based on that.. but this looks like ugly!
In order to accomplish code reuse, usually I implement everything in a inner class. This way I can choose what to do in each case just once.
If you've done something very general, you might do it in a separate file so you can reuse it in other classes.
I think you should spend a little time familiarizing yourself with the basics of object orientation before you go further - you are doing yourself a disservice because without the basic understanding, you are probably going to write a ton of code that in the end, wouldn't be needed if you had the basic understanding. Pick up a beginning Java book or do a tutorial or two online - you will be glad you did.
And I hope you don't take my advice to be picking on you - I am simply telling you that your question indicates you don't know the basics.
Now to answer your question... You want to create a single class that implements all the shared event handling logic (shared code means only the code that all activities will use). You will then use this shared event handler from each of your Activity classes by making your activity classes either an IS A EventHandlingClass or HAS A EventHandlingClass. Now its up to you to find out what IS A or HAS A actually means, and when you do, you will then have the basic understanding of object oriented languages.
Good Luck!
Rodney