Android: Intended use of fragments with services, dialogs etc - android

I've been creating android apps for a few months now and I'm having trouble with the intended use of Fragments.
Fragments are supposed to be reusable UI components but how far do you make them stand alone?
One of the Fragments I've created is a ListFragment of downloadable videos. At the moment I've implemented all the methods inside the Fragment with little or none of the methods calling the host Activity. The Fragment calls the Activity for a few minor things but everything like downloading files and finding them on external storage is done by the Fragment.
90% of the time I find it's the easiest way of implementing it but there's some times it just doesn't work.
An example is a confirmation dialog for deleting a video in my ListFragment. The dialog is a DialogFragment so is attached to the Activity but all the UI update and deletion methods are inside the ListFragment. So I end up with the DialogFragment calling the Activity just to call the ListFragment.
Another example is binding to a Service. Do I bind the Activity to the Service or just the Fragment? The Activity has no use for the Service but is a Fragment supposed to be doing all the work of starting and maintaining a Service? If not it means all the Fragments calls to the Service have to go through the Activity so the Fragment is no longer stand alone.
I'm wondering if I'm taking the stand alone idea too far, is a Fragment instead supposed to be minimally self-contained and actually rely on the Activity hosting it for all the heavy lifting?
Thanks for any help.

A very interesting question!
I usually try to keep my fragments as isolated as possible. That means I usually don't let them know about anything around them except for their own activity. It's then the activity's role (if you ask me) to provide what-ever-is-needed to the fragment.
In practice this means that my fragments never own their own content, like a content provider or a custom DAO. The activity (or - God forbid - the application) owns it and then provides only a subset of the data, like a cursor, a domain object or an adapter, to the fragment.
This also means that when a fragment modifies an item it has to ask the activity to persist the changes. Or if an item is to be deleted, the fragment has to ask the activity to show the corresponding UI for that operation (yes, it's technically possible to let a fragment show another fragment, but I usually try to avoid it as far as possible).
When it comes to services and binding to them I really don't know what to suggest as it really depends on the service and what it's doing. If you're downloading new content from the internet in your service, then it seems rectified to let the activity handle the binding (as it is the activity that needs to save the data, according to previous discussion). If you, on the other hand, are calculating something specific, based on your isolated data (e.g. decrypting a file or so), then it might make sence to let the fragment handle that part.
In an even greater perspective one soon realizes that a setup, such as described above, will give birth to quite some callback interfaces as each fragment needs to establish a contract to its activity. Hence, for smaller projects it sometimes happens that I override my very own fragment-pardigms.
I also can't help noticing that when using fragments, my applications tend to be very MVC oriented in their architecture. I leave it to you and any future readers to decide wether it's a good or bad thing ;-)
Cheers

Related

Communicating between fragment and parent activity

I have a fragment with a list view on it, and the user is able to select items in that list. Whenever at least one item is in a selected state I would like to reveal a "delete" toolbar button on the parent activity. Would I just raise an event from the fragment to achieve this?
What about doing the deletion - should the activity or the fragment be responsible for this? Either way the activity would need to somehow ask the fragment to either do the deletion, or ask it to reload the list (if the activity does the deletion).
Really looking for best practices for this kind of activity/fragment communication, and to reduce the coupling (presumably interfaces will play a part too).
For a second (related) question, my fragment is currently responsible for retrieving the list's items from the database, but in a book I've read they show the activity doing this instead, which then passes the items to the fragment. What are the pros and cons of each approach?
As an answer to all of your sub questions, keeping the classes loosely coupled and linking them using an EventBus is the ideal way to go for!
EventBus allows publish-subscribe-style communication between components without requiring the components to explicitly register with one another (and thus be aware of each other). It is designed exclusively to replace traditional Java in-process event distribution using explicit registration.
This seamlessly allows you to pass data as event to multiple classes and listen to those events from multiple other classes as well. To see the usage, see this Answer

How to organize Android App code?

First of all: I am rather new to Android App programming and I have a rather basic question:
Already with the sandbox app I am currently working on, the code in the Activity class get quite huge because all the callback methods / listeners (click listener, callbacks from GoogleApiClient) are in there (either by implementing the respective interface or by creating a private class). But I would rather put those into separate classes.
But the question that I ask myself is this: how would I then be able to access the class attributes of the activity class? Sure, I would then probably create setter/getter, but still I first need a reference to the Activity object. How would I get this?
Thanks and regards!
It's a really wide question, since the answer depends by your project and by your programming style. The first suggestion is: move what you can move in one or more fragment. All stuffs related to google play services can be nicely handled in a fragment for example. Listener and callback are UI related components, so they need a Context of an Activity to work, but you can split your UI (again) with Fragment and keep a piece of logic in a Fragment and another piece somewhere else. If you have some logic that runs in background, then you should consider using Service. I tend to have empty Activities, but this is not a rule.

Activity and fragment responsibilities in network communication (robospice)

I am creating apps using Robospice library. It is great choice to handle internet connections, because core of the library is based on Android Service, so our connections are not tied to the Activity life-cycle.
We are creating our requests and executing them with spice manager which in turn is instantiated in each activity (Base Activity inheritance) , I don't is it right way to place creating of manage object here, if there is better way to do this, please let me know.
public class BaseActivity extends AppCompatActivity implements ActivityController, SpiceManagerProvider {
private SpiceManager mSpiceManager = new SpiceManager(MyRobospiceService.class);
I have been creating request (robospice requests) exactly where I need them in fragments and activities. But now I thought a little bit about this. Maybe it is better to separate request handling only in activities. And just listening for button clicks or whatever from fragments in activity with callback methods or some other inter component communication. And than in activity make request, handle it. But in this case if I need to get data back in fragment I have to send it back from activity to the fragment. So it seems a lot of redundant communications.
All in all I wan't to get advice from more experienced developers about separation of responsibilities, should I handle request in only one component (like activity) or I can make and handle requests anywhere I need this.
Thanks everyone in advance.
Using a single SpiceManager per Activity and sharing it between Fragments is what I have successfully done in the past. You have to, unfortunately, check if the Activity is still resumed in this case for every response listener.
To be specific, you need to be sure that you will not update a stopped or destroyed UI.
See related FAQ question for more details.
The second paragraph there mentions the the other approach of having a SpiceManager per Fragment, so that should be a viable option for you as well. We noticed some overhead while creating SpiceManagers (this only hurts when there are many Fragments) and therefore abandoned it for our use.

Is it a good idea for a Fragment to delegate all navigation control to Activity?

Inspired by the Android developer guide I am trying to write code in which all fragments are self-contained (in terms of network/logic) and any actions they perform (click/tap) which should result in launching a new activity/fragment would be delegated to the activity (through callback).
To begin with, it seemed right. But now , when I have fragments which have more than 1 such widgets (which need the fragment to navigate to a new screen), it seems like a mess. I either need to write multiple callbacks or do some switch-case logic in Activity for different actions done on a fragment.
If this design sounds bad, what are the scenarios where implementing callbacks (as suggested by the guide) would be a good idea ?
I don't know how you are implementing these callbacks.
One approach to this problem is to use the contract pattern:
The fragment defines a Contract interface, that any hosting activity must implement
When the fragment wants to pass control to the activity, it calls a method on that interface
Jake Wharton has the canonical implementation of this in a GitHub gist. The only piece that is not shown is that the activity that hosts his MyCoolFragment needs to implement the MyCoolFragment.Contract interface.
This assumes that each fragment has distinct events to raise to the activity and therefore needs its own interface. If you have several fragments with common characteristics, you could standardize on a single interface, rather than duplicating the Contract everywhere.
There are other approaches (e.g., the comment on the gist suggesting using a message bus), but for simple fragment->activity communication, the contract pattern should have the least overhead, both in terms of coding and runtime implementation.
Your general approach, though, of delegating work to the activity where that work may result in changes to another fragment, is definitely a good one. It makes it that much easier to handle the cases where the fragments are not on the screen at the same time, perhaps hosted by different activities, as you handle different screen setups (phone vs. tablet, single screen vs. displaying content on a connected TV, etc.).

General structure of android app

Im searching to make a simple android app that can do two things:
Show incomming bluetooth data on a graph
Send user defined data back using a textbox and a button
I'm using the navigation drawer, and loosely based on a tutorial, I've set up a GUI with two fragments, each running their own activity.
My question is now, where would I put all the bluetooth related stuff? Each fragment must be able to both send and receive data, will I have to implement the bluetooth connection in each activity? Can I implement it in one activity (e.g. mainactivity) and reach it from the other activities? Is there a better way to do this (i.e. two fragments from one activity)?
Update:
Maybe I'm confusing myself a bit. What I currently have is a main-activity, (extends Activity) that starts one of two fragments (extends fragment) by calling
fragmentManager.beginTransaction().replace(R.id.container,
MyFragment.newInstance()).commit()
So this is actually one activity only, I guess. Question is still, will I put bluetooth related stuff in the mainActivity, or in the fragment-classes that are created. Do I even need the fragment-classes, or can the xml-fragment layouts be handled from within the mainActivity instead?
You probably want to implement a Service, which you can reach from any of your activities or fragments.
Alternatively, you can have a singleton object somewhere which manages this connection, but this can create more complicated lifecycle issues, so I would recommend simply using a service.

Categories

Resources