Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android - strings.xml vs static constants

Tags:

Here's what I'm thinking:

The strings on strings.xml should be use for the layouts (xml) to use. And static constants are for codes (.java) to use.

When it comes to best practices, I'd like to know which should be use.

If you have lots of strings, will it have performance effect?

getString(...) vs MyConstants.THIS_IS_A_CONSTANT 
like image 918
lorraine Avatar asked Apr 23 '13 02:04

lorraine


People also ask

Why do we use string xml in Android?

xml , you can easily translate your whole app into other languages. This saves you a lot of work instead of doing this the hardcoded way: Android automatically selects the correct language based on user preferences, and you don't have to worry about selecting and displaying this language.

In which folder can you find the string resource file strings xml?

You can find strings. xml file inside res folder under values as shown below.

How do you declare a constant string variable in Java?

To make any variable a constant, we must use 'static' and 'final' modifiers in the following manner: Syntax to assign a constant value in java: static final datatype identifier_name = constant; The static modifier causes the variable to be available without an instance of it's defining class being loaded.


1 Answers

There are both some advantages and disadvantages ( I should say advantages and less advantages) in these two cases.

as in the comments of your question they said it all. I just want to add some minor points.

Localization:

For localization issue definitely String resource is the best as you can use different language file for differente Locale.

Memory:

As String resources are saved in xml file so there are some extra overhead (not a major one though)

Performance:

reading from memory is always faster than reading from file. Although in this case the performance difference is not significant

Maintainance:

It is just a personal opinion. To me maintaining res file is easier than maintaining string in class. string.xml is more readable to me.

Finally:

So my suggestion is

use string resources for the texts which will be displayed to user.

and

use static constants for internal puposes of your program like database names, internal variable, intent filter name etc.

like image 87
stinepike Avatar answered Nov 09 '22 11:11

stinepike