I have developed some apps for Android, and this questions stays always:
How should I structure my UI? Should I launch activity after activity and leave the phone to make the "back" button, or should I choose more optimized, but more complex to implement, way with switching manually Views and then manually doing the "Back" button functionality?
What do you think (or know) is the better practice?
I would say that multiple Activities almost always makes more sense. I just don't think Android is designed for constantly switching its own views - you miss out on so much. You have to implement Back yourself, you don't get any inter-Activity transitions, you have to implement a lot of internal logic to resume an application in the correct state. If you don't partition your app into Activities, it makes it a lot more difficult later on to change the flow of your application. It also results in one mega-Activity that can be a lot harder to handle than a lot of smaller pieces of code.
I have trouble imagining that speed is really an issue; if it is then there's something wrong with the way you're initializing each Activity. For example, I used try to pass Serializable objects between Activities, and that proved to be incredibly slow; when I switched to a faster method of passing objects, the speed of launching Activities increased immensely.
Also, I think it's telling that the Android guidelines for Activity and Task Design don't mention switching Views at all; it's centered around an Activity-as-View design.
I'd like to point out some instances when a single activity might be better design for an Android application that has more than one full screen View:
If the application screens are tightly coupled and share a common Object that they are all operating on. In this case passing around the Object may require a Bundle and can be error prone since there will be copies of it. A good example might be a wizard. Yes you could use static's to access the common Object but static can be dangerous in Android (think configuration changes!)
If you want some really cool animations in between screens. Maybe you want a bird to take off in one screen and land in another screen. Try doing that when each screen is an activity!
On the other hand if one of your screens is designed to be shown by any number of other applications then that screen should be its own Activity.
UPDATE March 2014:
At this point the question should now include the choice of Fragments. I think that Views are probably the least likely choice of the 3: Activity, Fragment, View. If you want to implement screens that make use of the back button then it should be either Activties or Fragments because both handle the back button natively. Fragments will need to be added to the FragmentManager back stack for the back button to work. Managing fragments, dialogs and the back stack can be a bit of an annoyance though!
UPDATE Sept 2018:
Some devs at Google are recommending single activity apps using the new navigation architecture component.
Also keep in mind that implementing your app with multiple Activities will give the user a more coherent experience with the platform as a whole. Part of the experience will be shaped by using the built-in Google apps, so users will probably have an easier time using your application if it behaves similarly to the ones that are already installed on the phone.
Different from others I use a mixture of both, for example,
1. There is a main menu when the application starts
2. You click on search, takes you to search activity
3. Then there's a filter button, which just switches view and shows you filter options
4. There are two buttons at the end of the filter view, You hit "Search" or "Cancel" and you are back to the Search View again (without switching activity)
5. Now if the user hits the phone back button he's taken back to the main menu instead of the search filter options. Which I guess is the correct behavior.
Use it the way user will feel natural. And keeping everything in one activity will make it complex.
It all depends on application, what are you trying to achieve better performance, smoother UI. IMHO I prefer the second approach of controlling the Activities manually even that it is more complex as you have stated. This is a approach I have used in my android tabs project, also you might want to take a look at a class called ActivityGroup (not sure the package) it allows you to have multiple activities that you can switch between, good thing about this class is that your activities are not unloaded when you switch but a bad thing is it takes longer to load your main app.
Just my opinion.
The problem with switching views, that I stumbled upon, is also caused by garbage collector. Seems that GC is triggered when you leave activity and not the view. So, changing tabs with a fairly complex children views, for instance, will almost inevitably lead to stack overflow exception..
I've experienced so many problems with multiple activity layout that I strongly discourage it, unless there's good reason to pick it.
Disadvantage of multiple activities
Using multiple activities it is much hard to refactor code to return data from activity.
If you call a 'sub'-activity then the main activity may be killed. But you never experience that while debugging on a decent device, hence you need to handle always saving state and correctly recovering state. That is a pain. Imagine calling a method on a library (ie. another activity), and you would have to be ensure that when that method returns your app must be able to recreate its state completely with all fields on all objects in the VM (ie. activity.restoreIntance). Its insane.
Also the other way round, when you open a subactivity the VM might have been killed since the subactivity was first spawned, such as when app is minimized while subactivity is displayed.
Its so much cleaner to just have one place to store the relevant app-state, and in my case, most often if VM is killed, I want to return user to main-screen, and let them do their stuff again, because I don't spend 30-50 hours coding save/resume functionality that 0.1% of users will ever experience.
Alternative
Fragments or just manage you activity views yourself. Managing views manually, requires coding some view-switching alternative to activities/fragments with transitions if desired.
And no it does not mean one mega-activity, as suggested in the accepted answer, in any other way than its one mega-app. It just requires a bit more design of the codebase into fitting pieces, because there's slightly more work managing views, though much less work managing activity-state and other weirdness.
Possibly relevant: Reddit: It's official : Google officially recommends single activity app architecture
Related
I know this question might not be one which has just one correct answer. But letting me know, that there are several solutions with good reasons for each of them, would already help a lot. So here we go:
I have designed an app which manages persons along with measurement data for each person. The data can be displayed in a chart. Generally this leads to the following tasks:
Person: Add
Person: View
Person: Edit
Person: Delete (more an option with a security dialog than a real screen)
Measurements: View (List)
Measurement: Add
Measurement: Delete (again more an option with a security dialog)
Measurements: Plot (in a large graph view)
The app will run on a phone at first. I have read that an activity is supposed to serve a very limited purpose, so the scenario would lead to one activity for each task.
However, when the app is displayed on a tablet in landscape mode, I can imagine to have three sections on the screen at once:
One section in the top right cornern managing persons
One section below that listing the values for the selected person
One larger section on the right part of the screen to plot measurements
I often read that I should avoid to create god activities. On the other hand I read that fragments is the way to go, so that each screen can easily be displayed as a subscreen on a tablet, as it is planned here.
I started off with creating the app for mobile phones, so I created one activity, which juggles all fragments (almost one for each task) in a single fragment container.
Is this the way to go, when I want to do it by the book?
I was wondering whether I should create a separate activity for each task. For the phone this makes things easier. But on a tablet I would have to control the fragments from one single activity anyway, correct? So in that case a god activity it needs to be?
You are definitely on the right track, but there are some things you may want to look into.
In my opinion Activities should only be used to host Fragments and transfer events between Fragments. Basically, the only logic that you should have in your Activity is handling the navigation. The logic stays in the Fragments (or some other layer, used by your Fragments) and it is not exposed to the Activity at all. In that way there will be no need to duplicate any logic and make some Activity a "God" Activity.
Good that you started thinking about it. You should always prevent god activity. Read about MVC, MVP & android architecture patterns which help you avoid creating a god object.
I'm just getting to know Fragments in Android.
When you create a new blank project, by default a Fragment is included as well, although it's not really used. My impression is that Google wants you to use Fragments all the time no matter how simple the app is. Would that be a true assessment or can you think of any reasons not to use Fragments?
What I also find strange is that the documentation indicates that Fragments can also be used for stuff that is not UI related. Can you give me an example of an app that would use a Fragment but doesn't provide any UI?
Google introduced fragments when they lunched Honeycomb (3.0).
As you may know, Honeycomb was the first Android version to support tablets out-of-the-box and they use fragments to better arrange UI layouts on the screen.
With Fragments you can utilize screen property way better then with activities. One activity can run and "command" many different fragments that share same screen real-estate and the fragments can be swapped on the fly.
So yes, Google WANTS you to use fragments and it is the right way to write most scale-able applications.
As for the second question:
Fragments can persist across configuration changes - like screen orientation changes for instance. Activities gets killed and recreated when you change screen orientation and any work they might do will have to be recreated again.
If you use fragments right, then when you change screen orientation the activity might get killed but the fragment can persist its state and then re-attach itself to the newly created activity and continue where it left.
Basically, if you have an AsyncTask running from an activity and the activity gets killed because of orientation change (for example), you AsyncTask is useless now. But if you hold the AsyncTask through a fragment then it will continue because the fragment isn't destroyed.
Hope this helps
It all depends on what you're developing and how. I don't think EVERY app needs to have fragments, but they are in many cases easier to work with as they can be swapped on the fly, managed by a single activity, etc.
For instance, imagine your app has some background task running, and you want it to keep running while the user is still "Free to roam" around the app. Running that task in the activity and having the UI in fragments would be a very simple way to do this. The activity can also manage and send messages and data to its "children" fragments at any point, including communication between the fragments themselves.
As for fragments with no UI at all, I don't recall coming across something like this, but you can definitely implement background tasks and other methods that are not directly related to the UI in a fragment. Again, it all depends what you're developing and how. There's really no "right or wrong" here...
As Android documentation states: "An activity is a single, focused thing that the user can do."
However with Fragments we will be able to do many "things" within the same Activity as Reto Meier suggest. His suggestion is to replace a selection fragment by a content fragment within the same Activity (section "Within our code this produces a dilemma").
Lets say my application is a "bit" more complex, with many activities, with a complex navigation tree and designed with the "single, focused thing that the user can do" principle in mind.
Lets say now I have to adapt it to Fragments and large screens... and that I don't want to create a second application, neither have two completely different logics (one for phones other for tables) inside one application.
Should I have one Activity to manage all the application fragments and fragment transactions? Like Retro Meier suggest above. Is that the recommended path to follow? Thus breaking with the "single, focused thing that the user can do" principle for Activities?
Or am I missing something? I hope ;)
BTW, I think Fragments looks great, but from what I have seen till now, only if you are creating an application from the scratch. Because making applications to be compatible with phone and tablet looks like going to be a bit tedious. Hope to be wrong :)
Dianne Hackborn already has answered (thx for the link mgv):
you could put your entire application in one activity in which you change the fragment structure as its state changes
So then Activity becomes a sort of container where you will be able to plug Fragments. I like the approach, but... in my app there are about 30 different operations available, each one requires about 2 to 4 screens steps to be performed(forms and selection lists), all of them differ and there are also navigation restrictions. It works fine with Activities each one handling one screen/step behaviour.
So then to port to Fragments I should move each screen logic to Fragments and use Activities as containers for each operation. Thus leaving Activities as the ones managing the navigation between Fragments for every operation, right? Looks like going to be a pain to adapt long applications. :(
Current Activity definition should change a bit btw. :)
Should I have one Activity to manage all the application fragments and fragment transactions?
That is impossible to answer in the abstract. However, most applications will have multiple activities, even in a fragment-based world. Some of that will be to accommodate smaller screen sizes, where it will tend to be one fragment per activity. Some of that will be required by the framework (e.g., inheriting from PreferenceActivity). And, some of that will be by GUI design.
Thus breaking with the "single, focused thing that the user can do" principle for Activities?
That portion of the documentation was written in 2008, perhaps earlier. Had fragments existed back then, I imagine the documentation would state that a fragment is a "single, focused thing that the user can do", with activities serving as an orchestration layer, determining what fragments are visible in what circumstances.
The documentation will not in all places be updated to reflect fragments, and even if it does, it will take some time. For the balance of 2011, at minimum, you will need to perform your own translations of 2008-era instructions to convert them to 2011-era fragment-based UIs.
Lets say now I have to adapt it to Fragments and large screens... and that I don't want to create a second application, neither have two completely different logics (one for phones other for tables) inside one application.
I have no idea what you consider "completely different logics" to be. In a fragment-based app, most of your business logic will be in the fragments themselves. The activities, again, serve as an orchestration layer, determining what fragments should be visible and coordinating event handling. The latter will get a bit more complicated than it used to be, since sometimes clicking on an item in a list will bring up a new fragment and sometimes clicking on an item in a list will start a new activity, depending on screen size.
Or am I missing something?
To be honest, you are missing enough concreteness to your question to make it reasonably answerable.
Does anyone know of a way to show another class without creating a new instance?
It seems a bit crazy from a memory management point of view that each time you want to display a different form / page you need to use StartActivity which then creates a new instances of the class instead of reusing instances previously created.
Thanks in advance
I guess from what has been said - there is no real way to do it which won't hinder the "Back" functionality of the OS?
I'm building an app which is linear except on each screen it has a home button which then makes it possible to countermand this functionality and end in a loop - is there anyway you know of to destroy all over views and reset back to the main class? (IE prevent a memory leak from becoming a problem but also not damaging OS functionality)
Consider it a "clear history" without restarting the app
Not sure if this would work for Android (coming from a MS/C# background), but conceptually one option is to iterate through open forms looking for one with a specific handle. Then, once you find it, simply call the method to show that form. This would depend on there being a Java equivalent to the Application.OpenForms property in .NET.
It seems a bit crazy from a memory management point of view that each time you want to display a different form / page you need to use StartActivity which then creates a new instances of the class instead of reusing instances previously created.
Tactically, you are welcome to add FLAG_REORDER_TO_FRONT to bring an existing activity back to the foreground, so long as you understand the ramifications from a navigation standpoint.
However, your question is rather curious. How are you accessing StackOverflow?
Clearly it's not via a Web browser. Web browsers use the exact mechanism that you feel is "crazy", rendering Web pages even if that Web page had been viewed previously. They have been doing so for over 15 years, and we've been doing OK by it.
The Android navigation model is designed to approximately mirror that of the Web:
Users click on things to move forward
Users click on a BACK button to move to the previous thing they were looking at
Users click on a HOME button when they want to switch to some other major thing to go look at
By "reusing instances previously created", you're circumventing that navigational model. For example, let's suppose your activity stack were A-B-C-D, and you call startActivity() with an Intent for B and FLAG_REORDER_TO_FRONT. Now, the activity stack is A-C-D-B. When the user presses BACK times, they no longer are on the B they were looking at originally, but are back at A. In a browser, this would be rather strange behavior.
There are other flags on Intent, or attributes on <activity> in the manifest, that offer "reusing instances previously created". However, they are not there "from a memory management point of view". They are there where the traditional Web BACK-heavy navigation pattern does not fit your needs.
Assuming you aren't screwing up anywhere, Android will destroy under-utilized activities, garbage collect that memory, and even return that memory to the OS.
I seem to be missing something obvious here, why would I want more than one activity per application in Android? Does somebody have some solid examples?
Suppose you are creating a game. You need to have at least two activities - a welcome screen, and the actual game screen. The third activity in this example might be a settings page of the game.
Another example.
Suppose you are developing an application and you need to pop up a dialog, i.e. asking user to set username and password (Standard login screen). You might choose to create and activity and apply a dialog theme to it.
Think about it as the form of desktop application. you don't put everything on one form do you? :)
Sorantis' answer is spot on. Here are other thoughts as well:
Most Web applications, even AJAX-y ones, don't try to have everything in one single page. Some do, and those tend to be the ones that are slow as molasses to load (Evernote, I'm looking at you), have code that looks like a heaping mound of spaghetti, etc. Android is no different.
Also, state management for a super-complex Activity will be nasty, causing you problems with screen rotations and supporting being kicked out of RAM because you screw up onSaveInstanceState(). Memory management in Android assumes lots of cheap activities, not fewer massive ones. Intelligently handling the BACK button requires gobs of your own logic. If you want multiple entry points (e.g., Launcher icon and a MIME type handler and something some other app can call with startActivityForResult() and a search results handler), doing that in one activity will be a nightmare. And so on.
One very basic thing that makes having multiple activities in your program desirable is the use of the back button. I have a form in app after the user clicks search he is presented with another activity showing the results of the search. If he wants to change the search parameters he just can press back and without me doing anything particular he gets back to the search form. Doing this with one activity would be a lot of work for you.
The next thing is the memory management. Android will trigger the garbage collection automaticaly after changing activities that means my whole search form leaves the memory and doesn't take any resources away from the user.