Does hard coding of string affect performance? - android

Whenever I make any app I always hardcode the string instead of referencing it from string resource from XML. App works fine but gives me warning to use #string resource
Example button:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click here" />
My question is whether it will affect my application performance if I do so or it(#string resource) is just used for internationalization.

This is an Android lint warning to help you with localization.
Technically, hard coding strings would make your app perform a little better, as it won't have to look up the string from the corresponding R int each time. However, this performance difference will be negligible, and no human will be able to notice it.
However, you should always keep your String resources in the values folder as it makes localization very easy.

I see no reason that you would get worse performance by using a hard-coded string. There are fewer steps involved with hard-coded strings. However, it is certainly best practice to separate resource strings from application and UI code.

It will not create any performance issue. But defining strings in strings.xml is encouraged for the ease of maintainance and lolalization. For example consider the below two scenario.
Scenario 1
When you need to change a string used in many places. In your case You will have to change all the "click here" in all layouts. But if you declared in strings.xml then only change made in the xml will change them all.
Scenario 2
For another example if you want to show different language for different locale then you need to use the string.xml.

As others said, it's for localization,
but for performance, it depends on how many times per second those strings are getting looked up.
I've seen a case where an app is slow in startup, and stack sampling showed 50% of the time was being spent in resource lookup of strings, and the reason the strings were being looked up was to display them on the splash screen that gives the user something to look at while the app is starting up!

I dont think hardcoding a string will make your program to run any slower.. Infact it will enhance the performance as there's no need for any lookup for the String in the R.java class.
Referencing the string from strings.xml is best practice due to 2 reasons:-
1- Localization
2- if you're using the same string in multiple places and would like to edit the same in all the places saves you the overhead of editing all the hard-coded strings individually.

Hard coding strings will not affect the performance directly. It affects the maintainability.
In case when you hardcode a string and in later stage if you want to change the string "Click me" to "add" or something else, then you need to search your complete project to change the string where and all it is used. So Better to follow strings.xml always. :)

Your app will not support Localization then, if that is not the requirement of your app then there will be no problem using hard coded strings.

Related

Pros/Cons of setting text with setText(R.string.value) and setText(getResources().getString(R.string.value)

I can set text by simply doing setText(R.string.value), for example. I receive no compile or runtime errors. I learned this by mistake, as I always use to set text by getting my string values from resources, such as setText(getResources().getString(R.string.value). What is the difference? Has Android evolved to where it no longer requires the getResources() method? Will older devices be compatible?
This has actually been possible forever if you look at the TextView documentation: https://developer.android.com/reference/android/widget/TextView.html#setText(int)
There are also some other setText(…) methods in there which you might check out.
I'm generally never using the resource id's directly to display the text because it's like your said not generally known and causes some distraction for people not used to it. But I don't think that there are any benefits/drawbacks from using either of these two.

Android resource vs hardcoding

I know using a resource is good for redundant uses like any label that is generic across a platforms application but are there any other benefits to using a resource instead of hard coding?
for instance I have a button that is only in one view, is there a benefit to using a string resource for the buttons text even if it is one button that is only in one place in the entire app?
Otherwise I feel like its easier to go in to the one specific view to find the button and change the text if i need to rather then scrolling through an entire resource file to find one string resource.
There is more than one reason for using strings.xml than hardcode it. Please read the localization documentation. It allows you to easily translate text into many languages as you provide.

what happen if do not put text files in string.xml in android?

i did not put some text in string.xml and there is a yellow alert symbol in side of Textview field. i want to know does it have problem and what happen, if do not put texts in string.xml in android?
Well, setting your text directly on your layout file can be a source of future problems and its not recommended.
Consider this scenario: You use the same string "Foo" in many layout files and then you decided to change to "Bar". If you have hardcoded that, you will need to make changes in all layout files and there might be a chance to leave some inconsistent text. But if you place it in the strings.xml file, you will have only to change in one place.
Also, if you want to add translations to your app, the Android system can handle it automatically for you if you use the strings.xml.
You might want to take a look here and here.
Nothing will happen.
string.xml used to:
localization
res/values-fr/strings.xml
res/values-ja/strings.xml
ease of editing and to save memory when reusing.
I Recommend you to put text files in string.xml
Whilst it will not cause a problem in the short term, it is not good practice and will cause you issues in the future if you decide to support multiple languages.

Differences between android:text="#string" and android:text="..."

Maybe this is a silly question but is there a difference,besides the obvious,between
android:text="#string/...." and android:text="..."?.I'm thinking that maybe the text that appears on the screen has the option for styling when using #string.Which one is best to use in general or it really doesn't matter?
When you're using android:text="#string/" the app is going to find the value of the string in the ressources file, with this technique you can manage multilanguage app, with a "strings"'s file by language.
Choice Matters, if your app has a lot of text in it, supporting a different language would be easier if you used #string, you would not have to scramble through every xml file to add text in the other language for every piece of text, simply go to strings resource and change there.
But then again, when checking UI for errors after work is done, it might make life harder (or work boring) as fixing a typo would require you to go to the xml file that the erroneous text is located, look up the name of string and then go to Strings to correct (unless you were very organised and named things well in your Strings such that you know which text belongs where)

Are there conventions on how to name resources?

Are there conventions how to name resources in Android? For example, buttons, textViews, menus, etc.
Android SDK will be a good place to start.
For example, I try to scope IDs within the activity.
If I had a ListView it simply would be #android:id/list in all the activities.
If, however, I had two lists then I would use the more specific #id/list_apple and #id/list_orange
So generic (ids, ...) gets reused in the R.java file while the unique ones (sometimes gets reused) get prefixed with generic ones separated by an underscore.
The underscore is one thing, I observed, for example:
Layout width is layout_width in xml and layoutWidth in code, so I try to stick to it as list_apple
So a Login button will be login, but if we have two logins then login_foo and login_bar.
I don't know whether there are any official recommendations.
For ids in my layouts with widgets and containers, I use the convention:
<layout>_<widget/container>_<name>
I do the same strategy for any dimens, strings, numbers, and colors I use in those layouts. However, I do try generalizing. e.g if all buttons have a common textColor, I won't prefix the name with the layout. The resource name would be 'button_textColor'. If all textColors are using the same the resource it will be named 'textColor'. For Styles, this is usually the case as well.
For menu resources i use:
menu_<activity>_<name>
Animations are only different as you cannot use uppercase letters. Same goes for drawable xml resources, i believe.
Taken from Android's documentation. There is more there on the subject.
To answer your question: Yes, there are.
You can find many of them via google search for example. And there is no such thing as the best naming convention. It always depends on your needs and your project attributes (most importantly the scope).
Recently, I've read quite good blog post about naming resources in Android XML from Jeroen Mols. Author mentions the basic principle all resources should follow and then how this convention is applied to each resource type. Both described on Android resource naming cheat sheet:
He then describes each element and each resource type in detail.
I would say you could use this convention from small to medium projects (personal use, few months contract applications). Although, I would not recommend it for long time projects with like 50+ activities or 1000+ strings.
Conventions for resource values in projects of such a large scale requires more investigation on how they will be used. Take strings for example. Might be affected by size of your team, translation center you are using (if any), VCS you are using (to avoid merge conflicts for example), etc. You might even think about splitting strings into multiple files.
I assume you are looking for something to begin with. So I would recommend the blog post I mentioned. It's good for starters and you can definitely use it as inspiration to create good naming conventions of your own.
Also keep in mind that as a project grows, many needs and requirements may change in time. So its completely normal that naming conventions that were suitable in the beginning will not be suitable after 2 years. And it's completely fine. You should not try to predict future. Just choose a convention and follow it. You will find if it is suitable for you and your project. If its not, think about why it is not suitable and start using something else.
There are a few conventions used in resources:
For resources that exist as separate files, they must be lower_case_underscore_separated. The appt tool makes sure that your files are only lower-case, because using mixed case can cause issues on case-insensitive filesystems.
For resources declared only in values/... (attributes, strings, etc) the convention is generally mixedCase.
There is a convention used sometimes to tag names with a "classification" to have simple namespaces. This is for example where you see things like layout_width and layout_alignLeft. In a layout file the attributes for both the View and the parent layout management are mixed together, even though they are different owners. The "layout_*" convention ensures that there are no conflicts between these names and it is easy to understand which entity the name impacts.
This "layout_blah" convention has also been used in a few other places. For example, there are "state_blah" attributes which are the drawable states a view can have.
Also because of these two conventions (underscore_separated for files, mixedCase for declared resources), you will find a number of inconsistencies. For example colors can be declared with either files or as explicit values. Generally we'd like to stick with underscore_separated for all of those, but it doesn't always happen.
Ultimately we don't worry a whole lot about naming conventions for resources. The big one that we keep consistent is "mixedCase" for attributes, and the use of "layout_blah" to identify layout param attributes.
Also browsing through the public resources here should give a good feel for the conventions:
http://developer.android.com/reference/android/R.html
You'll see the attributes are all quite consistent (given you understand the layout_ convention), drawables are all underscore_separated, etc.
This is a common problem to any language or framework, but so long as you avoid reserved words you should be ok assuming you can remember what you have called things.
I did note that Android places a restrction on xml resource file names but underscores seem to be ok. ADT actually states
File-based resource names must contain only lowercase a-z, 0-9, or _.
Something that tripped me up at first was a lack of namespaces with id's, but this can generally be ignored if you have two id's the same Android will just reuse the defined id.
For id's I use a 3 letter qualifier followed by what it refers to in camel notation e.g lblFoo for a static text label (or textview), txtFoo for an editable textbox (edittext in Android). This may seem odd at first but I've been using it since VB6 and those controls were called label and textbox.
Here are some more I commonly use:
btnFoo - button
pwdFoo - password
lstFoo - list
clrFoo - color
tblFoo - table
colFoo - column
rowFoo - row
imgFoo - image
dimFoo - dimension
padFoo - padding
mrgFoo - margin
I use the same in code within the java file too so I don't have to think about it, package scope will allow this quite happily:
Button btnFoo = (Button)findViewById(R.id.btnFoo);
You could if you prefer add a little spacing using underscore i.e btn_foo ... I probably would do this if I could break old habits.
There are those who may argue that abbreviating these may not be ideal and the purists would argue that the full name should be used, but when you are naming dozens of controls and changing between different systems and frameworks, the full names lose their meanings, I have used these for over a decade in VB, C++, ASP.NET, WinForms in C# and VB.NET, Android and Python. I never need to remember if Android calls it a textbox or an edittext. All I need to know is that lblFoo is the static label and txtFoo is what the user types input into.
One final note is that no matter what convention you decide upon the important things is naming controls properly and consistently, so that you don't wrestle with vague default id's e.g TextView5 or a mixture of different conventions
Useful link for designer and developers - here
Dimensions and sizes, naming conventions, styles and themes, nine-patch and so on.
I don't think there is any standard convention promoted by Google. I've seen all kinds of different ways people name stuff, even within different official Google apps.
Whatever helps you the most when trying to make sense of a 100 layout (or drawables, menus, etc.) files in one directory hierarchy.
A short answer: if you would like to learn from Android developers, a good example is the support library v7 (https://dl-ssl.google.com/android/repository/support_r21.zip)
Otherwise, here's what I have considered for naming resources:
1. finding resources easily when writing code
2. understanding resources easily when reading code
3. making names useful for translators (R.string.* resources only)
4. reusing layouts with <include/> (R.id.* resource conflicts)
5. dealing with library projects
Logically, arranging resources should be no different than grouping java classes into packages (or putting files into folders). However, since Android resources have no namespaces, prefixes must be added to the resource name to achieve the same (e.g. com.example.myapp.photo becomes com_example_myapp_photo).
I suggest to divide the app into separate components (activities, fragments, dialogs, etc.) with short unique names that can be used as resource prefixes. In this way we're grouping resources with related functionality together, which makes them easy to find (point 1) and we're at the same time avoiding naming conflicts with both <include/> and library projects (points 4 and 5). Note that resources common to multiple components can still have a prefix (such as R.string.myapp_ok_button).
After the prefix, the name should tell us what the resource is used for (action to be performed, content to be displayed, etc.). Choosing a good name is important for understanding (points 2 and 3).
Sometimes "component_name" will give us enough information, which is especially true if the type is already given by the R class (in R.string.myapp_name_string the 2nd "string" is redundant). However, explicitly adding type can improve understanding (e.g., it can be helpful for translators to distinguish between a toast, or a label). Sometimes the "name" and "type" parts can be swapped to allow type-based filtering (R.string.photo_menu_* will give us only menu-related items for the photo component).
Let's say we're writing an activity for taking pictures, class com.example.myapp.photo .PhotoActivity. Our resources could look like this (grouped by the component "photo"):
R.layout.photo //if only a single layout is used
R.menu.photo
R.string.photo_capture_instructions_label
R.id.photo_capture_instructions_label
R.id.photo_capture_button
R.id.photo_capture_image
R.drawable.photo_capture_placeholder
R.dimen.photo_capture_image_height
If you poke around in Android's documentation, there are various mentions of "best practices", but there are certainly no concrete rules. For example, in Icon Design Guidelines, Google suggests naming icons with a "ic_" prefix.
A good place to start may be Providing Resources.
Also dig around in the SDK source/examples as well as on the Android Developers Blog if you want to see how the Google developers do things.
I found handy next naming convention for strings:
[<action>]_<object>_<purpose>
For example, clear_playlist_text, delete_song_message, update_playlist_positivebutton_text. And "action" here is optional.
I generally followed the java naming conventions for resource ids(not for files for files) except I added "x" in front of the ids for example:
<TextView android:id="#+id/xTvName" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
In java
we can use it simple(we can also rememberin simple)
TextView mTvName=(TextView)findViewById(R.id.xTvName);
Here mTvName(It is in general android suggested naming conventions) and xTvName which was named in layout file as part of android TextView's Id(x meant for XML),I followed this type of naming conventions for view objects such as Buttons and EditText etc.
in XML IDS:xViewTypeSpecificName
in Java:mViewTypeSpeficName
The above conventions makes my life easier when I create complex layouts.
Just try to make your names as much as possible short in length and it is better if they are understandable and meaningful to other co-developers(but it may not possible every time),Hope that my experience will help others,suggestions are welcome.
In our android projects there are lots of components like buttons, labels, textboxes. So simple name like for example "name" this is very confusing to identify "name" is label or textbox. Mainly it happen when you are maintaining projects developed by some other developers.
So to avoid this kind of confusion I used following names for Buttons TextBoxes or Labels
Example :
btnName
labName
txtName
listName
May be this is helpful for you.
you can read the google documentation for code style to get an idea here
There are some restrictions:
Resource name should contains be a-z,0-9,_
Resource name should start with a-z,_
By the way, it is more advisable to follow the guidelines or to learn from standard code.

Categories

Resources