Android Best Pratice to reuse code and layout - android

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.

Related

Should similar screens be different Fragments?

Ok so I'm creating an app. I have a "Creation" page, and a "Detail" page for the same item. The UI is the same, probably the logic will be the same as well, only difference i can think of now is that when creating, the Object backing my UI is local, and as an argument in the fragment I get the item "Name", when showing the detail, the argument is the item's "ID" and the data backing my UI is remote.
My question is, following clean architecture and all around good programming rules, is it better to separate this screen in 2 almost identical Fragments, separating concerns and allowing for future differentiations, also possibly avoiding a "god fragment" but having a lot of possible code duplication, or is it better to keep them in the same screen, avoiding code duplication?
From my experience, you should avoid code duplication as much as you can. I don't know how deep and complex is your app, but if you have two almost identical fragments, I would use a 'ParentFragment' that contains the common code, and extend your Fragments from it. This way you can customize both fragments in the future, while maintaining the common features.

Standard for Android Activities

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 :)

How and when to use Fragments in applications?

I am very in doubt of the structuring of my application. When to use Fragments is a big question for me still. I understand the concept of fragment, but I would like to know how more experienced programmers use them. Is it really only when there is a specific task the fragment should do?
For instance, POP-UPs, what layout would be better used?
And back to the fragments, do you usually have a skelleton fragment that can be used for more than one thing, and then reshape it to different final forms (minor changes) or would you just use different fragments if the layout changes?
You should use fragments in a few situations but its going to depend on your app really.
If you have a layout that is going to be used in multiple places and the code is relatively the same, that is a very good candidate for a fragment so you can keep code down.
If you are making an app where the layout changes based on orientation or device type (tablet vs phone) then fragments are highly recommended to hold different layouts. It makes it easier to change or show multiple layouts if need be on a tablet.
I'm sure there are more scenarios but I would say these are the basics for fragment decision
The most common way I use them is as a kind of plugin layout for my activities. Let's say I have several activities and all of them need to display an address, phone number and some buttons (call number, launch navigation/gps, etc). I pass the fragment the id and the fragment does the legwork of grabbing the information and populating fields for my activities. This way, if I need to add anything, say an email address, I just need to modify one section of code rather than each activity and layout file.

When to use fragment backstack vs. individual activities?

I've been developing for Android for a couple of years now, and I still find myself going back and forth on this issue: when should I be using fragments on a backstack versus putting each fragment into its own activity?
In the Android Fragment documentation, they show this diagram:
I understand the tablet use case perfectly, but for the Handset use case, I don't get why you would put each fragment into its own activity. I typically create one activity and add the fragments to the backstack (via FragmentManager). Is either one of these approaches considered the 'right' way to do it? If both are okay, what is a good rule of thumb to use for picking which approach to use?
This question is closely related, but I'm not totally satisfied with it. If you're supposed to use separate activities, what's the point of having a fragment backstack in the first place?
I doubt there is a right way to do it. There are likely some ways that are better than others in some circumstances, but for the most part, the answer will be "it depends."
I have noticed in the latest version (22.x) of the SDK with Eclipse that every Activity that is generated is nothing more than a placeholder for a Fragment. The Fragment is auto generated and contains the view logic. It seems like they want to make Activities nothing more than a placeholder/controller for Fragments. I don't think I agree with that. While I definitely see the use case for Tablets, I feel like this pattern should be used more on an as needed basis than as a general rule. This is just my opinion, but I think moving ALL of the logic into the Fragment sacrifices some of the benefits you get from using an Activity, so it is only a useful pattern if you need to re-use that fragment specifically.
If you're supposed to use separate activities, what's the point of having a fragment backstack in the first place?
Good question. I personally prefer to use many Activities and only use Fragments where I need to re-use the logic/views in multiple places. I think the flow of using startActivity and startActivityForResult and allowing the system to manage your activity stack is just a little easier than trying to manage a huge Fragment back stack and one Activity (again, just my opinion).
So when would I ever use the Fragment back stack? There was actually a very good situation for me to use it recently. I had an Activity that needed to build a very complex object. The Object needed many fields input to the user, so I created a Workflow that walked the user through this process one step at a time. I created a single Activity to handle the creation of this logic. Each step of the UI was a Fragment that took input from the user, reported back to the Activity, then the Activity loaded the next Fragment. The Fragments were added to the back stack so the user could go back to previous steps in the workflow.
Object1CreationActivity
FragmentA --> FragmentB --> FragmentC --> FragmentD
Communication between the Fragments and the Activity should be done with interfaces. This is important if we want to re-use these anywhere else. Because of this, I could re-use much of this code to create another Object.
Object2CreationActivity
FragmentB --> FragmentD --> FragmentE
To summarize, Fragments, Activities, the back stack, these are all powerful tools you can use to make Android applications. There may not be a great rule of thumb for when and how to use them, but as long as you are well versed in how they work together, you can use them as appropriate for your application.
fragments are light weight alternatives to activities....that is one way to look at it. e.g. i have my our app which has about 10-13 screens. Either
I create a new activity for each one of them. OR
I create only a few activities that are logically distinct in functional aspects ad swap view screens in them OR
I create 1 activity and delegate actual screen functional to fragments.
I find the third way much better and manageable. Its kinda saying that fragments allow reuse of view using the framelayout options. Further more you can devise an easy way to share data between fragments as against the heavy weight way of using a Parceable to share stuff between activities.
Also Android API folks are going to focus more on fragment based designs instead of activities so its better to stick with standards. Using fragments i a just a tad more complicated than using activities but is well worth the effort to learn them. Helps create scalable and quiet reusable screen views IMHO.

To fragment or not to fragment?

As I've started to adopt Fragments more and better but also as Fragments functionality is increased (Fragments in Fragments, MapFragments) I'm starting to reach a point where I need to define when I should make a new View/Action as a Fragment or as an Activity?
An Activity is defined as:
An activity is a single, focused thing that the user can do.
But a Fragments have kinda taken that definition instead as described in the docs:
For example, a news application can use one fragment to show a list of
articles on the left and another fragment to display an article on the
right—both fragments appear in one activity
This is two things the user can do in one Activity with two Fragments.
So I'd like some input/help to figure out what is the best approach to decide if I should make a new action/view as a Fragment or as an Activity?
The answer depends on you and your development practices (or those of your company). However, my opinion is this: At a minimum, if you think the functionality being developed could be used within multiple Activities, or if it could ever be used in an Activity alongside another view (as on a tablet), then you should make it a Fragment.
We've recently adopted the philosophy of creating Fragments in all cases. Our Activities are now just top level coordinators, basically the glue that brings things together. This makes for a consistent and flexible architecture. This is important to us as we have numerous engineers at a couple of locations working on code.
An Activity is defined as: "An activity is a single, focused thing that the user can do"
That is more an issue of dated documentation than anything else. Activity has that same definition... when we are on a smaller screen size (e.g., phone). As you move up to larger screens, the odds of an activity being more complex than "a single, focused thing" increases.
So I'd like some input/help to figure out what is the best approach to decide if I should make a new action/view as a Fragment or as an Activity?
Here is my general heuristic:
If you anticipate that such-and-so piece of UI might exist standalone on a phone-sized screen, but be used in tandem with something else on a tablet-sized screen, make it a fragment.
If you anticipate that such-and-so piece of UI will always exist standalone, just create a simple activity.
If you anticipate that your ability to anticipate is not that good, err on the side of making more fragments. For example, you might say, "well, help will never need to be alongside anything else" and make it be an activity. Then, if you realize that other pieces of UI might benefit from the help being side-by-side with them rather than off on its own -- so the user can read the docs and perform the actions at the same time -- you will regret not having made help be a fragment, as you will have to do some re-work.
If such-and-so piece of UI would never exist standalone -- in other words, if it is more like a single widget than a full activity -- and you anticipate using it on multiple projects, make it be a single widget, in the form of a custom View or ViewGroup.
But, as jsmith indicates, there is no universal right or wrong answer. BTW, AFAIAC, jsmith's answer is the correct one here, but I was going to be way too wordy for a comment on his answer... :-)
I've been developing in Android since 1.5 so I have been developing from quite some time Activities and recently Fragments.
Quite frequently fragments left me with a sour taste in my mouth... an example was when I needed a kind of paginated Dashboard with buttons. For that I used a ViewPager + 1 fragment per button. I had all kind of problems because before Android 4.2 fragments couldn't be nested.
Another problem was the asynchronous mode of function of the fragments that when the needed to be moved from one place to the other quite rapidly it had all kind of misbehaviours.
Don't think that all was bad... in more simple cases, the use of fragments worked quite nicely.
So, in my opinion, whenever you have an area that is self-contained, that isn't moved frequently on the views, that can be reused in several screens and also you support tablets (or my in the future), use it.
If you need nested fragments, views that are re-arranged quite frequently, or code that will not be reused, don't.

Categories

Resources