tiny sunlight
tiny sunlight

Reputation: 6251

How should I store common strings?

I can store them in res/strings

<resources>
    <string name="str1">app</string>
</resources>

And I can store them in static const

public static final string str1 = "app"

Which one is better?

I mean that which one will use more memory and which one will make package larger.

Upvotes: 4

Views: 482

Answers (3)

Avijit Karmakar
Avijit Karmakar

Reputation: 9388

  1. If you have to change some text in your app's view, then you don't have to find where you have written that text. You simply go to the strings.xml in res folder and can change the string. For that reason, the first option will always be the better option.

  2. If you want a string that will be used as a key in your app then you can store it in a static constant variable. Like: If you want to pass data through intent or in any other way, at that time you have to pass a key. That key will be a string and can be stored in a static constant variable.

Upvotes: 3

Sina Rezaei
Sina Rezaei

Reputation: 529

The package size:

I believe that "Ran Hassid"'s comment describes well about the package size.

Memory usage:

Just create an android apk file with some static final strings and then decompile it. You will see that the variable has no initial value in the compiled version and the value is replaced in all references!

For example check this sample from my decompiled apk which is also obfusicated by proguard:

public static String f10850f;
...
...
...
hashMap.put(C1554f.m14687a("\u0014]SCVQ^V"), str);

here is the actual code I have written:

public static String packageName="\u0014]SCVQ^V";
...
...
...
hashMap.put(EncryptorClass.decrypt(packageName), str);

In this case, the static final String variable in my written code has value of "\u0014]SCVQ^V" but it is not used in run-time and just copy/pasted in related pieces of code.

So using static final String variables needs no memory because variable has no initial value.

Have a look at android docs about using static final variables

Also take a look at this post regarding memory of variables with no value

Overally, I use static final variables and string resources for different purposes like code encryption, language support and whether I want to access the variable using a Context or not.

Upvotes: 1

Ran Hassid
Ran Hassid

Reputation: 2788

it's really depend if you treat strings as constants or not. If you string are constants (e.g. string that will be sent as key of intent) then you can either create some Constants class or define it as a constant in your activity/fragment class. If those string are texts that will be displayed on your application UI then they should be defined as resources in your application. BTW all the resources string can be localized to different languages

If you need more info or examples please let me know.

Upvotes: 1

Related Questions