I am working with Android Fragments pretty extensively and one of the problems I am having is the lack of proper mechanism to pass complex objects to it.
In the android developers documentation for Fragments, they have a static method called newInstance called with some simple arguments which will be packaged into a Bundle and used inside the Fragment. However this method cannot be employed for passing complex objects.
Because I have been using the Fragments api a lot, it is becoming more and more important to have complex objects passed to it. One way to do this is by implementing the Parcelable interface, which I don't want to do for all the classes.
So, I thought I could do this :
Define an interface like this in the Fragment:
// Container Activity must implement this interface
public interface ReceiveDataInterface {
public MyClass getData(uniqueFragmentID);
}
Force the Activities using this fragment to implement the interface and call ReceiveDataInterface.getData(getArgument.getString(UNIQUEID))
In the Activity instantiate fragment using the newInstance method by passing a uniqueFragmentID and implement the ReceiveDataInterface which gives data based on uniqueFragmentID.
Is it a good idea to do this? if not, why? and how should I go about doing this?
Note:This is done in the same lines as OnArticleSelectedListener described in the documentation.
Any help is much appreciated.
We use this approach for any app we build for android. It works well. I havent tested every method of doing this, but i think this is among the best way.
Another approach would be to make the Fragment themselves independent. Why not write the code that fetches data from network/database in the Fragment itself?
Related
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.
I have a method inside of a class called
ChopraWisdom.GetQuote()
that pulls in some data from the interwebs. To use it I have to use an AsyncTask in my activity. Thats fine and all, but my Activity code now gets cluttered with the AsyncTask code.
I was hoping that I could hide the AsyncTask in my Class and then create another method called
ChopraWisdom.GetQuoteAsync()
But I'm not sure how to pass in "Actions" (I come from a .Net background) in order to handle the various UI updating that needs to take place.
In C# I would define the method signature as something like:
ChopraWisdom.GetQuoteAsync(Action preExecute, Action postExecute, Action updateProgress)
Questions:
Does java have something comparable to 'Action'?
What is the acceptable pattern for 'wrapping' Async functionality like this in Java?
I like clean code, but am I being to picky here?
Please provide examples.
EDIT - Added Example class
public class ChopraWisdom
{
public string GetQuote()
{
//...do stuff and return a string
}
}
You should really think about using Loaders instead of AsynkTask(with android support lib).
If you still want to use AsyncTask in your situation best way would be to create new interface Action(something like https://github.com/ReactiveX/RxJava/blob/1.x/src/main/java/rx/functions/Action0.java)
You could use RxJava in your project and use all they have https://github.com/ReactiveX/RxJava/tree/1.x/src/main/java/rx/functions
You could use https://github.com/evant/gradle-retrolambda in combination with (2) option to provide C# like lambdas in your java code.
Java does have something comparable to Action. It is called Function and only available in Java 8. The standard way for passing a function as parameter is to create an interface and provide it as a parameter. That way you can either pass in an instance of a class implementing that interface or create an anonymous class inline. You encounter the latter everywhere in Android (OnClickListener, etc ...)
I would highly recommend you to take a look at Android Annotations. It provides useful features like:
Dependency injection
View injection
OnClickListener via annotation
AsyncTask via annotation
...
And the best thing: everything is done at compile time through subclassing, therefore there is no performance impact and you can check what the framework is doing at any given point.
You are not too picky at all. Clean code is very important in Android development as you have to write a lot of boilerplate- / gluecode anyway.
Here are some other handy android frameworks that are definitely worth checking out:
GreenDao
Eventbus
I was going through vogella's fragment tutorial and I came across this method call in the MyListFragment class:
listener.onRssItemSelected(newTime);
However, this onRssItemSelected method is actually defined(implemented) in the RssfeedActivity class. SO my questions, how did MyListFragment class know to go to the RssfeedActivity class to find the onRssItemSelected method?
Most likely he is implementing a callback to allow the fragments to communicate with each other. The following link explains the process much better than I ever could:
http://developer.android.com/training/basics/fragments/communicating.html
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.
I have the following problem:
I have an abstract Activity class, lets call it MyAbstractActivity, that contains some code I'd like to reuse (for example: a standard service binder, common menu items, common initialization code, etc. etc.). Normally I would just use it to subclass my concrete activities and be done with it.
However, I occasionally need to use another supertype, such as a ListActivity or a MapActivity.
So the question is: how do I avoid duplicating that support code within an Activity, if I have to use another base class?
I have thought up of a solution based on the decorator pattern, like this one:
.
However, I see a problem with this approach:
What to do with protected methods (like onCreate())? Should I introduce an additional "bridge" class that makes them public for the purpose of the decorator, similarly to the way presented below (starting to look a bit byzantine...)?
Any other way?
I hope I made myself relatively clear. Thanks in advance for any feedback!
PS. Using static utility classes is not a good solution in my opinion, since it introduces a possibility of hard-to-identify programming bugs.
If I understand correctly, neither Fragments nor the Decorator Pattern are clean or appropriate solutions for what you want to accomplish. They were designed to solve other problems.
I find myself moving "support" code, or "framework" code, or "all that verbose, repetitive, boilerplate crap" to static utility methods. This isn't necessarily the approach I'd take on a non-Android project, but in my Android projects, it works pretty darn well.
Also, know that you don't need to subclass ListActivity to have a ListView.