Wrap Activity in a fragment, or an alternative solution - android

I have a kinda big, already published railway schedule app published on Google Play, and now I am planning to integrate bus schedules as well. My question is something like this:
At the moment, whenever the app starts, it loads the Activity, where you can search for train, lets call it A
I have already implemented a beta version of the bus search Activity, lets call it B
Eventually, I will come up with a hybrid solution, that will be able to search for trains AND buses at the same time, of course with some restrictions, lets call it C
Now, I want to implement the main screen so it will have swipeable tabs, and the tabs would be A, B, and C. I never really worked with theese kind of tabs, so my knowledge is not that deep, however, I came up with a solution, that would indeed work, but it is going to need a lot of recoding(keep in mind, my app was published more then a year ago), since I never really prepared for fragments. I am doing pretty much THIS thingie, and it works really great. However, this means that the main screen should be a FragmentActivity, which is fine, I can deal with that. But I just cannot supply A, B, and C Activity, as tabs, it will accept only fragments.
The question is: can I supplement my already coded Activity as a fragment, so I can swipe between them? Is there any wrapping mechanic I am not aware of? Any other solution, which you can show me? Just point me in the direction, I will do the rest. Or, am I f**ked, and have to recode everything from scratch? No problem, if that's the case, tho I would happily avoid it.
Thanks in advance, cheers. :)

What you can do is to wrap your fragment in an Activity. This would be the better choice if you've got multiple classes enclosed in your Activity. Otherwise, I would just go with wangyif2's suggestion instead.
In any case, should you want to do the former:
public class SampleActivity extends Activity {
...
public static class SampleFragment extends Fragment {
...
}
}
And when you finally initialize all this in an ActionBar
final ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.addTab(bar.newTab()
.setText("Sample")
.setTabListener(new TabListener<SampleActivity.SampleFragment>(
this, "sample", SampleActivity.SampleFragment)));
I suggest checking out the API Demo from API 14+ samples. There's a really good example of this in FragmentTabs (com.example.android.apis.app.FragmentTabs).

Thank you both for the suggestions, I did try the method wangyif2 suggested, it generates way too much overhead in the code, since I did some kinda specific things.
I am going to check out some demos, but I guess I will recode everything from scratch, that seems to be the most clean solution at this point.

Instead of your original Activity A, B, C extending SherlockActivity, simply change them to extend SherlockFragments, and supply them to the Tabs.
Obviously there will be some compilation errors that you have to fix, namely the difference between activity lifecycle and fragment lifecycle, but once you fix them, you should be good to go.

Related

Using a no-fragment activity instead of a one-fragment activity

While peer reviewing a colleague's code I noticed she created a new Activity and all functionality is just there without a Fragment.
In the old days of Android, this is what we did, but the last few years I and my peers always took the approach that every Activity should have at least one Fragment and no actual code should be written in the Activity apart from loading the Fragment of-course and maybe some higher end procedures.
I want to argue for always using at least one Fragment in every Activity, but I couldn't find compelling arguments about why it is better than a no-fragment Activity.
The out of the box argument I can think of is that it will be easier adding new fragments if needed, but if we know this will never be a necessity, why bother with a single fragment Activity?
Fragment is easier to extend and test, if you are writing another new feature, it is helpful for separating code. And you can also move your fragment code to another place easy.
Of cource, if you are sure that your code is very simple and stable, like demo or temp test code, you can also use Activity without fragment.

Always use fragment

In Big Nerd Ranch's Android Programming, it advocates AUF (always use fragment). Specifically, it has this to say:
"...adding fragments later can be a minefield. Changing an activity to
an activity hosting a UI fragment is not difficult, but there are
swarms of annoying gotchas. Keeping some interfaces managed by
activities and having others managed by fragments only makes things
worse because you have to keep track of this meaningless distinction.
It is far easier to write your code using fragments from the beginning
and not worry about the pain and annoyance of reworking it later, or
having to remember which style of controller you are using in each
part of your application."
The book doesn't expound on what the annoying gotchas are. What are the gotchas?
Biggest of all is Context. as Activity is driven by Context (not directly). when you need context in an activity you have it there all the time. same is not with the case with fragment, in fragments you can call getActivity method to get parent activity but when porting code from Activity to fragment you have to deal with supplying it everywhere.
Another problem could be life cycle of Activity. where activity lifecycle is simple and functions like onResume, onPause are pleasure to use same can not be said for fragments. Adapting things which were designed for Activity life cycle into fragment life cycle can be nightmare.
Having said that, if things are not complex and you need to handle only one task it is safe to go with activity to begin with.
Because you are at the very start of decision making, I want to leave this here:
https://corner.squareup.com/2014/10/advocating-against-android-fragments.html
On the bottom line, this blog says that the lifecycle of a fragment is too complicated and therefore it advocates against using fragments, in favor of an Model-View-Presenter-Pattern
A personal note: the wordy comment from CommonsWare hits the spot. I blindly used fragments because they were there and I never questioned them. But after reading the above article, I've changed my mind.

Should we be using setTargetFragment()? I thought Fragments should not be communicating with each other

The android developer tutorials recommend me using the host activities of fragments to pass around data and whatnot, so why is there a set/get target fragment method?
My application thus far contains a host activity, and a fragment, which has a button that launches a DialogFragment, in which there is a button that launches ANOTHER DialogFragment. Using setTargetFragment/getTargetFragment has made this whole ordeal somewhat confusing though, so I am thinking of reimplementing to let my main activity handle DialogFragment.show methods through my main fragment's custom interface.
Is this the right way of thinking? Or is there no harm in using setTargetFragment? Can anyone provide good and bad examples of using it?
Also, you may end up with exception of no target fragment found in fragment manager. This happens if after rotation (or other config change) your target fragment will not be readded to the fragment manager by the time when caller fragment will be adding.
Imagine you have some sort of Confirmation fragment which you add from MainFragment as so:
ConfirmationFragment frag = new ConfirmationFragment();
frag.setTargetFragment(this, 0);
getFragmentManager().beginFragmentTransaction().add(R.id.container, frag).commit();
Now on some confirmation button click you invoke a method from MainFragment by calling:
((MainFragment)this.getTargetFragment()).onUserSelectedGoodButton();
This is pretty and simple, but if you will rotate the screen and for some reason ConfirmationFragment will be added to FragmentManager before MainFragment, exception will be thrown, stating that target fragment is not found in the fragment manager
I don't think there is implicit harm in using setTargetFragment, however, I would only use it in very specific circumstances. For example, if the target fragment is only going to ever be used by the fragment (taking into account object reuse and designing your classes to be reusable when possible) and even then, sparingly.
By using them too much, you will end up with what you're seeing - confusing code that is hard to follow and maintain. On the outset, by marshaling everything through your activity you maintain a "flat" hierarchy that is simple to follow and maintain.
I think the decision to use setTargetFragment or not is a coding-style/philosophical one that, with wisdom and experience, it "feels" right or wrong. Maybe on your case, by evidence that you are questioning your older code, you are gaining that wisdom :)

Activity or Fragment in Android?

I have been researching this for about an hour and cannot figure out whether to use fragments within an activity or start a new fragment activity.
Some sites make it sound as if you should have 1 activity and EVERYTHING else is a fragment. Is that the more proper way now? I can't figure out when you use an Activity (or fragment activity) and when you use a fragment.
I have an app for a conference with:
-Speakers (and sub views/activities/fragments) for each speaker.
-Schedule (different sections for each day)
-General info
-Sessions (different sections for each session).
So do I have 4 activities each with their own fragments or do I just use 1 activity with fragments and nested fragments?
You could do it either way, but generally it is best to use an Activity (or FragmentActivity) for each "screen".
If the user sees your app as logically a single screen that has little panels appearing/disappearing for different kinds of data, then use one activity with a lot of fragments. If the user sees it as "going to different screens", then you probably want multiple activities.
If you go with the one-activity-many-fragments model, you may find that your activity's code gets really complicated dealing with all the possible configurations of fragments. That is a good sign that you may want to split it into multiple Activities. Similarly, if you go with the many-activities model, but find that things get complicated as you pass shared data between activities, consider merging the activities.
Converting from Activity to FragmentActivity is as simple as changing the extends and nothing else needs changing.
My conclusions:
I stopped using Activity and only use FragmentActivity as it is more flexible and more up to date and backwards compatible (Using the support library).
If the FragmentActivity has a component that is large enough to be a standalone component, or needs to be one, then I make it as Fragment.
I haven't come across something that would require a complete separate activity to be within another activity, but that should only be used if that component is large enough and completely standalone enough to need an activity for itself.
I don't fully understand your app to be able to make a specific call on which you should use, if you want my opinion, can you provide more details on what you are working on and how are those components connected.
Regards
Another consideration in choosing a more decomposed architecture (many Activities) might be the cost of destruction / creation in the Activity Lifecycle. Do you plan to use Explicit/Implicit intents to leverage existing apps? More death. So, you might have only one activity in a dispatch oriented model and clearly see your apps logic in one place, but how much state will you have to save/restore? Are there performance penalties for re-inflating or populating data resources?

Everything on one Activity - Android

How do you think?
I think to create small app and put everything on only one Activity.
Just change the content Views. Get rid off problems with share data,
start from recent apps and couple more.
I know that in that way I can get much more problems, like stackoverflow.
But did someone try it?
My friend and I were making 1st application together and he insisted to make it like that..It was laggy, unstable and it can be characterized as "the worst practice" example..
I don't agree that it runs much faster, I agree that you need to do additional programming, which Android by default would handle automatically if u follow good practice (like BACK pressed) and I am sure that it will lead to a lot of memory leaks, unnecessary memory use, and decrease of performance. All in all it doesn't leave good impression to someone who is using it..
If you are doing it just to avoid sharing data and other "problems" it is much better to invest some time in this topics and try to learn more about them, to start using them in a proper way. When you know framework a bit better you will understand why such ideas of putting everything in one activity is bad.
moral I learned:
It is terrible idea to put everything in one activity, if your application in reality needs more components !!!
Blockquote
Choose your programming companion wisely!
Learn Learn Learn..
good luck ;)
Yes... it's definitely doable. However, it's a really terrible idea for anything other than the most basic apps. I had the same impulse when I was first starting out and built an app that had 5 screens. It quickly became much more trouble than it was worth, and that one activity had SO much code, it was a nightmare.
If you're targeting Honeycomb and > you should just use fragments. It's much nicer.
If your primary motivation for doing this is the complexity of passing data around from Activity to Activity you should consider extending Application and just storing all your persistant data (by that I mean the stuff you need while the app is actually running, not when it's backgrounded) up there.
If you're not doing any substantial interacting with the user and just want to swap out XML views with minimal functionality, you could be ok with the one Activity approach, but for most applications it's just too messy.
Yes, a couple of my first apps were made using exactly this approach. There are some advantages like:
It usually works a bit faster than changing from one activity to another.
You have just one Activity class.
and some disadvantages:
You may confuse yourself if you have too many screens.
You must code the screen changing logic yourself.
This is not considered as usual practice for Android development.
Anyway, this approach works, so it's your decision to use it or not. Hope this helps.
I would suggest you to use fragments. These fragments can be called through one activity. Although I am sure of that simple one activity will do, because I used one activity class for handling fragments, but i was using few more activity class also.
For ex. You can create different fragments and call them in activity like;---
public void onStatusClick(View view)
{
setFragment(new HomeFragment());
}
public void onNotificationsClick(View view)
{
setFragment(new NotificationsFragment());
}
public void onContactClick(View view)
{
setFragment(new ContactFragment());
}
public void setFragment(Fragment fragment)
{
FrameLayout framelayout = (FrameLayout) findViewById(R.id.frme_container);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(framelayout.getId(), fragment).commit();
}
If its the kind of project you can abandon after handover then you can get away with using one class
If however, your client is long term and will be requesting future changes and or extensions then it best not to dump everything in one class. Changes are hard to anticipate and you may find yourself refactoring everything if its all in one activity.
I agree with all of positives of using Activities and Fragments. My card-game app was initially written with 1 activity and 7 views. Eventually I refactored the application to use 7 Activities. The start up time of the application dropped significantly. However, when using 7 views, the app never had memory problems, and once loaded, was lightening fast between screens.
So my conclusion is that using views vs. activities (or fragments) is more of a trade-off than the slam-dunk presented by other answers. Views take longer to initially load, but are super-quick to swap. Activities are modular and are only loaded when needed. Memory is less and load time is quicker when using Activities, but the trade off is more complicated code and slower transitions between screens.
Finally, you don't have to use an all or nothing approach. You can always mix both solutions into your application, which is what I finally settled. I use Activities for screens that are infrequently used and Views/ViewSwitcher for the main 2-screens that are frequently used. Its the best of both worlds.

Categories

Resources