0

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

Patrick Coyne
  • 61
  • 2
  • 6

5 Answers5

4

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.

Gaurav Bansal
  • 604
  • 5
  • 11
1

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 use Constants.MY_CONST on your calls
Abner Escócio
  • 2,697
  • 2
  • 17
  • 36
0

You usually would store it in the xml file because that allows you to easily swap between files if you want to change languages

Sacha
  • 322
  • 1
  • 8
0

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.
NiVeR
  • 9,644
  • 4
  • 30
  • 35
0

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

Bita Mirshafiee
  • 600
  • 8
  • 14