Which is best way to define constants in android, either static class, interface or xml resource?

Jayabal picture Jayabal · Jun 22, 2012 · Viewed 79.1k times · Source

I'm developing an android application which uses web service to get data from server, for that I'm having three different set of URLs to point development system, test server and live server. It's difficult to change URL whenever I want to give application for testing/live. so I planned to make it as configurable, so that application can get appropriate URL based on me build type configuration constant. So,

  • which is the best way to keep this constants, java static class or java public interface or xml resource file.? When? Why?
  • which gives better performance?, When? Why?

Ex: xml resource

<integer name="config_build_type">0</integer>
<string-array name="url_authentication">
    <item >http://development.com/xxxx</item>
    <item >http://test.com/xxx</item>
    <item >http://example.com/xxx</item>
</string-array>

Java static constant

public class Config {
    public static final int BUILD_TYPE = 0; // 0 - development, 1 - test, 2 - live
    public static final String[] URL_AUTHENTICATION = {"http://development.com/", "http://test.com/", "http://example.com"};
}

Answer

Alex Lockwood picture Alex Lockwood · Jun 22, 2012

There is a big difference between the two in that you can reference project resources in your XML layouts. They are available in the application context and are therefore accessible across the global application. The biggest advantages of using project resources is the ease of access and that they allow you to organize your project significantly.

static final constants are compiled into the java bytecode; project resources are compiled into a binary format within the apk. Accessing either is extremely efficient... if there is a difference between the two, it is trivial at most.

There isn't a set rule on how you should be using resources/constants in your project. That said, I personally use resources for values that I might need to use in my XML or java code. On the other hand, I typically use static final constants for values that will only be used by my java code and are specific to my implementation.

Also note that it is possible to load XML resources at runtime depending on the device's current configuration (i.e. screen size, locale, etc.). So you should take this into consideration when deciding whether or not you should declare the constant in XML or directly in your .java files.