My app has a creation page and an edit page. These two pages are almost exactly identical, save the difference you can't edit without first creating the page. It's working perfectly fine, except it seems a little redundant have two separate activities with the same actions.
My question is, what is the standard/best approach to this situation. Should I create a new class, from which both these classes could access methods from or could it be one activity? Also, there is some amount of calculations, (a small series of random number generators) being carried out, should this be running on a separate thread? Or is it fine running on the main thread?
An example of what I have is kind of like android contacts app, you can create new contact and you can also edit that contact, which is essentially the the create new contact page.
Approach 1:
Have a Base Activity that extends Activity.
Then add all the common code like inflation of layout, some logic, life cycle handling etc.
Then create 2 classes like CreatePage and EditPage. These two new classes will extend the Base Activity.
Just handle the little variations in xml page dynamically here at runtime. Maybe in onStart().
This approach show cases basic OOPS of 1 parent Activity and multiple children.
Approach 2:
Have a Base Activity, and put create page and edit page as Fragments.
Just replace the fragments on your activity according to your program flow.
P. S. My answer may be a little abstract since your question is generic :)
Related
I've been reading about the include tag on xml, fragments to use on layout for smartphone and tablets but I'm getting more confused than getting a solution to my problem.
My App has 4 screens.
1 - You login and it download info from a json
2,3,4 - From login, Activity 2 load (A list with custom adapter), where you can click one of 2 images to jump to 3rd and 4th activity.
I need now to create the activity 1, 2, and 3 again with different JSONs being parsed, with 1 and 2 having the same layout of the existent ones and 3 with a different layout.
The code I need for them to work is(or can be) the same (Download Task with AsyncTask, button click listeners, etc) I already have for those activities.
I think it's not a goot pratice to copy basically the same getView method, for example, and paste on a new class, right? The buttons wouldn't work on the second range of screens for example.
So, what approach should I take that isn't copy and paste code and change things manually?
Sorry for the newbie question.
If needed I can provide code.
PS 1: I've already did tests with include on xml and copy code but that doesnt look professional
PS 2: Is fragments only for different screens like tablet or I could make something with it?
That's several questions, so here's several answers, including to some un-asked questions:
To the greatest extent possible, strive to remove as much code as possible from your Activities, Fragments, etc. If it doesn't have anything to do with the Android lifecycle or actually putting something on the screen (e.g. parsing JSON), put it in a "plain old java" class. Also, this way, you can share the functionality among Activities.
IMHO, you should never use an AsyncTask, for any reason. They're used with an Activity or Fragment, but don't respect the Fragment or Activity lifecycle, so are often the cause of crashes that can be difficult to diagnose. Use something synchronized with the lifecycle, like a Loader. Or go the RxJava route, where Subscribers can be canceled at the appropriate point in the Activity/Fragment lifecycle.
Fragments can be good for code re-use, but they have a slightly different lifecycle from Activities, so they can be difficult to work with, so use them sparingly and be careful. If you're doing it just to re-use a bit of UI (but not behavior), a layout "include" is probably better. For behavior, a custom View class can be a good alternative to a Fragment.
Don't do HTTP / REST access yourself, using primitives like HTTPUrlConnection. There are a lot of corner cases that are going to get you into trouble. Use one of the several really good open-source libraries that are built for this purpose. I highly recommend Retrofit.
Just a disclaimer, I am pretty new to Android and slowly working through tutorials. Most tutorials dont talk about fragments at all in the beginning, but Android-studio by default sets up one for you.
I've read some of the past questions and the dev blog related to fragments and activities and they were helpful in giving me an idea as to the advantages of using fragments.
I am still a bit confused on when one would use a new activity in an app, it seems to me like everything could be accomplished with fragments and a single activity.
Lets say an app has multiple screens, do you implement that as one activity with multiple fragments, or multiple activities with one fragment each to them.
This image makes sense to me and demonstrates the power of fragments, but why on the handsets example is two activities required?
Another add-on question, should everything moving forward be done in a fragment?
Thank you and sorry if these questions didnt really make sense.
An Activity should be the host for a collection of related Fragments. For instance, you might have something like:
Base Activity extends FragmentActivity
LoginActivity extends BaseActivity
-- LoginFragment
-- LoginErrorFragment
-- LoginSignUpFragment
SettingsActivity extends BaseActivity
-- SettingsGeneralFragment
-- SettingsAdvancedFragment
If you try to move all of your logic into a single Activity, it's going to get unmaintainable very quickly. Another good practice is to have a base Activity which all of your Activities extend; since if you suddenly find that there's some functionality you want to provide to all activities, you can just add it to the base class.
Everything said above in both regards are absolutely correct. I would just like to add few points to them.
When thinking about fragments please keep in mind that they are a part of an Activity, which like any other view can be added, modified and replaced dynamically. For example, while using ActionBar's and Navigation Drawers fragments become more handy and flexible. Similar things stands true for ViewPager etc.
Fragments also cater to larger screen sizes in a much better way than the traditional Activity approach. Imagine the users experience then when for every action performed a new screen would replace the Phone/ Tablet against now when all the actions and their performed events lie on the same screen.
One more thing which I like about fragments is, we dont have to declare them in the Manifest. :) Most of the time we forget to do that with Activities until the compiler prompts. :) (At least me)
As you said. In simple application you can use only one Activity and just replace fragments. I did it in my apps and it works perfect. Sometimes you just need to start new Activity if you want to follow android design and architecture patterns.
According to your question about images that you posted you can
obtain the same effects using just one Activity and Fragments.
Yes everything moving forward can be done in a Fragment.
This question already has answers here:
Dilemma: when to use Fragments vs Activities:
(17 answers)
Closed 4 years ago.
I often need the different parts of my applications to have their own special behavior and UI, and I don't know how fragments can help. In most cases, I think it is quicker to create 2 different activities (e.g., 1 for tablets and 1 for handsets), and to share the common behaviors and events in a third class.
So, keeping this in mind, why should I use fragments ?
Fragments are more of a UI benefit in my opinion. It's convenient for the user sometimes to see two different views of two different classes on the same screen. If, in your moment of creativity, you decide it would be nice to display your application with, say, a listView that takes up half the screen and a webView that takes up the other half - so that when you click on a list item in fragment A it passes an intent to the webView in fragment B, and suddenly you see what you just clicked without the app switching activities - then you could use a fragment. That's just an example I came up with off the top of my head.
Bottom line: Fragments are two or more activities on the screen at the same time.
The benefits I see when using fragments are:
Encapsulation of logic.
Better handle of the lifecycle of the fragment.
Reusable in other activities.
The drawbacks I see are:
More code(For example, instantiating a fragment manager, adding the fragment transaction, writing the callbacks of the fragment)
Communication between fragments and activities is harder. As #jonney said it, you would need to deal with a parcelable interface to serialize your objects you wish to pass.
So, when deciding to use a fragment, I would ask myself the following questions:
Is the lifecycle of the fragment different from the activity's lifecycle?
If the lifecycle is different, you get better handling of the lifecycle using a fragment. For example, if you want to destroy the fragment, but not the activity. Such is the case, when you have a pager adapter.
Is the fragment going to be used in several activities?
The user input events will be reusable if you use a fragment.
Is the amount of communication between the fragment and the activity small?
If you need to pass big objects to the fragment, you would need to deal with the code that serializes them. Also, if you need to communicate between fragment and activity, you would probably need to implement interfaces. This, in most cases, adds complexity to your codebase. It's not a difference maker, but a criteria to take into account.
Google advises you to ALWAYS use Fragments.
Why? It's simple:
In the simplest case, Fragments are used like containers of activities.
Why do you need this? Again, it's simple.
Android 4 (ICS) supports both Smartphones and Tablets. This means the SAME application will be running on a smartphone and a tablet and they are likely to be very different.
Tablets have big screens which will be empty or unused - unless you assign it properly.
That means- Putting two fragments on one activity like Contact List and Contact Info.
The smatphone will display contact List, and on a touch- display the contact's Info.
On a tablet, the user will still see the list and the info will be next to it.
2 fragments- on one screen....
Smart? yes... supposed to be back compatible down to Android 1.6......
#############################################################
O.K, Already Knew That? then - just try to understand the case solved:
A lot of things work that way- list & details, Menus and Sub-Menus, Info, Detailed Info and some more detailed info.
You want a way to keep it natural and smooth for a tablet which you expect to preform that way, but can't expect smartphone to display it all like the tablet did...
Get it?
for more Information, check out this.
I really think you just need to catch the concept....
Historically each screen in an Android app was implemented as a separate Activity. This creates a challenge in passing information between screens because the Android Intent mechanism does not allow passing a reference type (i.e. object) directly between Activities. Instead the object must be serialized or a globally accessible reference made available.
By making each screen a separate Fragment, this data passing headache is completely avoided. Fragments always exist within the context of a given Activity and can always access that Activity. By storing the information of interest within the Activity, the Fragment for each screen can simply access the object reference through the Activity.
https://softwareengineering.stackexchange.com/questions/244771/why-use-android-fragments
Fragment primary support more dynamic & Large UI Screen like Tablet.Because Tablet screen is much larger than normal Handset. There is more room to combine & Interchange UI Component.
Fragment allow such design without the need for such complex change in the View hierarchy.
By divide activity layout in fragment, we become able to modify activity's appearance at runtime
I have a very simple 2 screen android app.
Is there any downside to simply switching out the layouts via setContentView or should i be using intents?Don't want to bugger up my app if something is wrong with this.
Another thing to consider is that activities form a stack. If you want to be able to go back to the previous activity via the 'back' button, then you need to use activity. But if it is something simple like a 'loading' screen when your app starts and you don't have to go back to it again, setting content view would be a much better idea.
Well as stated on Android Dev http://developer.android.com/reference/android/content/Intent.html
An Intent provides a facility for
performing late runtime binding
between the code in different
applications. Its most significant use
is in the launching of activities,
where it can be thought of as the glue
between activities. It is basically a
passive data structure holding an
abstract description of an action to
be performed.
Therefore if your two screens are 2 different applications I would say you want to simply use setContentView.
it will simplify your code when you want to pass info from one to the other views
There is nothing wrong with having two views in a single activity. This approach is more light-weight, as you don't need to go through the phase of stopping one activity and then starting another one. However, it will make your activity code bulkier. Consider now if you are going to need more functionality or more views in the future and if the answer is yes, then it would be better to create separate activities.
If the view is light-weight (a bunch of text boxes), then it should not matter. On the other hand, if the two screens are largely independent and heavy, you could use two different activities. The primary advantages with this approach are:
If there is an error in the second screen (an activity in this case), your application will fall back to the first screen whereas in the case of using the view, the whole application crashes
Better readability
Easier to add more functionality in the future
I know how to functionally do each of the following scenarios, my main question is which is the better design decision? Based on app size/speed and battery life and such.
So I will have several activities that will display different lists. They're all lists of the same object, but the objects' states will be different in each of the lists. It will be lists of games, and the games can either be active, finished, or waiting to start. Should I create new activity classes for each of those? Or create one ListActivity class that will just display the different one depending on the intent that was passed? Is there a significant benefit to doing one or the other? Using a different class for each one will be easier to read, but what's the overhead on java for compiling more classes vs having all the same information in 1 class?
Create a base ListActivity which displays lists.
Then, create separate derived classes for each view mode.
You do want a separate Activity per view. Once a view isn't visible anymore, the OS can reclaim that activity. This helps resource management. Plus, when a view it an Activity it gets to do interesting things in response to user input (for instance, when the search button is hit).