Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hardcode string vs @string in Java code - Android

I'm just wondering what the benefits/overheads are for using @string rather than hard coding strings within the actual Java code... For Example:

// To get the string resource:
getActivity.setTitle(getString(R.string.my_string));

Is this the best practice for Things like Actionbar titles, Dynamically created button text, ect... Or should I just do this:

// Hardcoded string
getActivity.setTitle("My String");

I know there will be a bit more overhead doing it the first way.. Just not sure what best practice is.

like image 995
Gyroscope Avatar asked Nov 24 '12 04:11

Gyroscope


People also ask

Should Use @string resource in Android Studio?

You should add them to a string resource file and then reference them from your layout. This allows you to update every occurrence of the word "Yellow" in all layouts at the same time by just editing your strings. xml file. It is also extremely useful for supporting multiple languages as a separate strings.

What is hardcoded in Android?

In computer programming or text markup, to hardcode (less frequently, hard code ) is to use an explicit rather than a symbolic name for something that is likely to change at a later time. Such coding is sometimes known as hardcode (noun) and it is more difficult to change if it later becomes necessary.

What is hard coded string?

Hardcoded string are the literal strings. So, What you may be referring to is, literal strings in the data. C# Copy Code.

How do you Hardcode in Java?

Open the Settings / Preferences dialog Ctrl+Alt+S , expand Editor and click Inspections. Select the desired profile, and locate the node Internationalization under Java. Enable the Hardcoded strings inspection to highlight hard-coded string literals in the editor. Apply changes and close the dialog.


Video Answer


2 Answers

Incase you were unaware as to the actual point of having the @string system please read over the localization documentation. It allows you to easily locate text in your app and later have it translated.

Edit Thanks to Hippo for clearing this up.

Using multiple strings of the same value no matter the method (Strings.xml vs programatically) doesn't seem to have any associated overhead. According to Oracle "All literal strings and string-valued constant expressions are interned" which means that the object is reused rather than re-created if you use it again.

like image 99
KDEx Avatar answered Oct 04 '22 10:10

KDEx


That way you have a fixed place to alter all your strings within the project. Lets say you used same string in 10 different locations in the code. What if you decide to alter it? Instead of searching for where all it has been used in the project you just change it once and changes are reflected everywhere in the project.

like image 3
Shakti Avatar answered Oct 04 '22 09:10

Shakti