Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to store global constants in an Android application?

Tags:

I would know what is the best practice for storing global constants which can change with the environnement (debug, preprod, prod, release, etc) at compile time.

In iOS, I used to keep all global constants in a header file and change it with pre-processor macro see this answer:

Where to store global constants in an iOS application?

What solution should I use for Android ?

like image 688
klefevre Avatar asked Feb 25 '13 12:02

klefevre


People also ask

How to declare variable globally in Android?

Android App Development for BeginnersStep 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken text view to show global variable.

Where should I store constants Java?

Even if a constant is used throughout the code but always in relation to one class, it should clearly be part of that class (e.g. BorderLayout. CENTER).

How to declare constant in Android studio?

The key word final is used to declare a constant. Note that we can declare constants from any data type desired. In this case, we'll declare a double constant because our number contains decimal places. On a line between your two declared variables, declare a double constant named CENTIMETERS_IN_ONE_INCH .

What is constants Android studio?

Magic constants are a response to the ever-growing number of APIs in the Android framework, where the state, type of a component, or an action are chosen by providing an int or String constant. For example, setting view visibility with int constants or requiring a system service with String constants.


1 Answers

Create a class constants in your base package folder.

(or create an interface instead of a class so there is no need to reference the class everytime, however this is bad practice due to code readability, but it will work)

Fill it with public static final values.

Moreover, both the class as well as the interface can also be declared as abstract.

like image 170
Nickolaus Avatar answered Sep 17 '22 16:09

Nickolaus