I am wondering what is the best practice in defining constant strings in Android that are not changed for example I am using an analytics and need to access the information around the entire app. Should I be using a file like Constants.java where everything is a static string, an enum, or should I be storing that information in the strings.xml
5 Answers
Best practice to create a
Constants.java
and define your constants like below :
public static final int YOUR_CONSTANT_NAME = 14;//for the variables which will not change,
public static int YOUR_CONSTANT_NAME = 14;//which can be changed.
static - To keep in memory for complete app lifecycle, no repeated initialisation. final - as to keep the system sure that value will not change, once assigned.
In constants file, you can defined constant variables, Prefs name, API Keys, SDK keys etc.

- 604
- 5
- 11
XML
- Puting on xml file you will need a
Context
to access it. Then forget it.
ENUMS
- Enums aren't the best alternative to consts, why you will need use
toString()
s and casts to some cases. Then forget it also
Constants.java
- The best pratice is create an
Constants
class where you will put all constants and just useConstants.MY_CONST
on your calls

- 2,697
- 2
- 17
- 36
You usually would store it in the xml file because that allows you to easily swap between files if you want to change languages

- 322
- 1
- 8
In terms of performance there shouldn't be any noticeable advantage in either of those, or at least not to a point to make you choose one or the other without doubts.
I would say:
- In java code. When you will strictly use those in java code.
- In strings.xml. When you think that you will need those both in java code and xml configuration files.

- 9,644
- 4
- 30
- 35
If your variable won't change all through the process of your app, set it as for example:
Public static final String = "mystring";
In a java class say Constants.java.
But if your variable will change like a token in login and logout but you will use it for a specific amount of time, save it in, sharedPrefrences

- 600
- 8
- 14